melonjs-getting-started
Что он делает
Навык объясняет, как запустить игру на melonJS 20, включая обязательный шаг настройки и добавление первых объектов. Он нужен разработчикам, которые начинают новую браузерную игру на melonJS.
Когда использовать
- ✓Когда разработчик начинает новую игру на melonJS и ему нужен первый рабочий экран.
- ✓Когда объекты разработчика добавлены, но никогда не появляются на экране.
- ✓Когда разработчику нужно понять, какой рендерер будет использовать игра.
Ссылка на скилл
https://github.com/melonjs/melonJS/blob/master/packages/melonjs/skills/melonjs-getting-started/SKILL.mdСкопируйте и вставьте её в ваш ИИ (Claude, ChatGPT или Cursor) с просьбой следовать инструкциям.
Как использовать
Самый простой способ: скопируйте сообщение и вставьте его в свой ИИ. Он прочитает скилл и выполнит инструкции.
Готовое сообщение для вставки
Для Claude Code, Codex или Cursor: запустите в папке проекта, и скилл установится.
Скачайте SKILL.md и положите его в папку скиллов вашего агента.
Пример запроса к вашему ИИ
“Настройте базовую игру на melonJS с центрированным заголовочным текстом на экране.”
5 новых скиллов в неделю. 1 минута чтения.
Как это работает
Навык показывает порядок настройки: создать приложение, дождаться его инициализации через await, затем добавить объекты в контейнер мира. Он также объясняет запасной рендерер.
Технический текст (оригинальный SKILL.md)
Оригинальный текст автора на английском, прямо с GitHub.
Getting started with melonJS
Bootstrapping a melonJS 20.x game: the
Applicationlifecycle, the mandatoryawait app.init(), the world container, and what the renderer fallback means for feature availability.
Applies to: melonJS 20.x. Older major versions differ — see the
melonjs-20-migration skill.
The bootstrap
Application construction is synchronous but initialisation is not. init()
returns a promise and must be awaited before building any renderable, loading
assets, or entering a scene.
import { Application, Text } from "melonjs";
const app = new Application(1218, 562, {
parent: "screen", // id of the DOM element to mount into
scale: "auto",
backgroundColor: "#202020",
});
await app.init(); // ← REQUIRED. Nothing below works without it.
app.world.addChild(
new Text(609, 281, {
font: "Arial",
size: 160,
fillStyle: "#FFFFFF",
textAlign: "center",
textBaseline: "middle",
text: "Hello World !",
}),
);
This is the single most common thing to get wrong. On 19.x the constructor
called init(width, height, options) for you; on 20.x init() takes no
arguments and calling — and awaiting — it is your job. Nothing that follows
names the missing call. The constructor does build app.world, so adding a
plain renderable succeeds and simply never draws — no canvas is appended and the
app never subscribes to the frame tick — while constructing a Sprite or a
Text throws Cannot read properties of undefined (reading 'renderer'),
because the global game those two fall back on is only set once the first
init() resolves. Either way app.renderer and app.viewport stay undefined
and the page stays blank.
init() is asynchronous because acquiring a WebGPU device is asynchronous. There
is no synchronous alternative.
Top-level await
The bootstrap needs await at module scope. In an ES module that is fine. If the
surrounding tooling does not allow it, wrap it:
async function main() {
const app = new Application(800, 600, { parent: "screen" });
await app.init();
// …
}
void main();
Choosing a renderer
video.AUTO (the default) tries WebGPU → WebGL 2 → Canvas and uses the first
that works.
import { video } from "melonjs";
const app = new Application(800, 600, {
parent: "screen",
renderer: video.AUTO, // default; or video.WEBGPU / video.WEBGL / video.CANVAS
});
Two consequences worth knowing before writing rendering code:
- Which backend you get is a runtime fact, not a build-time one. The same code runs on a different renderer depending on the machine. Do not assume WebGL.
- Not every feature exists on every backend. Shader effects and post effects need a programmable pipeline and are inert on Canvas. Where a feature degrades, the engine warns once rather than throwing — so a missing effect is a console warning, not a crash.
Pin the renderer explicitly (video.WEBGL) only when you have a reason to. It
costs you the WebGPU path and the Canvas fallback.
The scene graph
app.world is the root Container. Everything drawn is a descendant of it.
app.world.addChild(sprite, 10); // 10 is the z / draw order
Pass the z-order as the second argument to addChild — it is the only form
that works. renderable.z does not exist as a property, setting depth before
addChild is overwritten by autoDepth, and setting it afterwards does not
resort. See the melonjs-renderables skill for the full explanation.
Scenes
For anything beyond a single screen, use Stage subclasses and the state
manager rather than mutating app.world directly:
import { Stage, state } from "melonjs";
class PlayScreen extends Stage {
onResetEvent() { /* build the scene */ }
onDestroyEvent() { /* tear it down */ }
}
state.set(state.PLAY, new PlayScreen());
state.change(state.PLAY);
onResetEvent runs every time the state is entered, not once — build scene
content there, not in the constructor.
Loading assets
Assets are declared and preloaded through loader; audio needs audio.init()
with the formats you ship before any audio asset is preloaded.
import { audio, loader } from "melonjs";
audio.init("mp3,ogg"); // BEFORE preloading audio
await loader.preload([
{ name: "tileset", type: "image", src: "data/img/tileset.png" },
{ name: "jump", type
Частые вопросы
Почему на экране ничего не рисуется?
В версии 20 приложение нужно инициализировать через await до добавления чего-либо, иначе объекты не будут нарисованы.
Что такое контейнер мира?
Это место, куда добавляют игровые объекты, чтобы они появились в игре.
Что такое запасной рендерер?
Игра использует WebGPU или WebGL 2, если они доступны, и переходит на Canvas, в котором нет некоторых функций.
Подробности
Оригинальное описание автора
Use this skill when starting or bootstrapping a melonJS game, creating the Application, choosing a renderer, or setting up the first scene. Covers the mandatory async init, the world container, adding renderables, and the WebGPU/WebGL 2/Canvas fallback. Triggers on: melonjs, new Application, app.init, app.world, video.AUTO, video.WEBGL, video.CANVAS, Stage, state.change, getting started, bootstrap.
repo: melonjs/melonJS
Популярность
- Звёзды на GitHub
- 6.4k
- Место в рейтинге
- #14203
- Лицензия
- MIT
- Обновлён
- 02.11.2026
Комментарии
- …
Другие скиллы из этого репозитория
melonjs-20-migration
6.4kПомогает агенту писать код игр на melonJS для версии 20 и не использовать устаревшие методы старых версий, например обязательный асинхронный запуск.
melonjs-3d-assets
6.4kПомогает агенту загружать 3D-модели, например файлы glTF, GLB и OBJ, в браузерную игру на melonJS с настройками масштаба и освещения.
melonjs-3d
6.4kПомогает агенту создавать 3D- или 2.5D-сцены в браузерной игре на melonJS, охватывая камеры, сетки, освещение и глубину, с правилами осей самого движка.
melonjs-audio
6.4kПомогает агенту добавлять звуковые эффекты и музыку в игру на melonJS, включая настройку аудио, фоновые треки, управление громкостью и пространственный звук.
Похожие скиллы
diffs
394kПозволяет агенту создать настоящее сравнение правок в виде ссылки или файла изображения, которым можно поделиться, вместо ручной сводки.
coding-agent
394kПомогает агенту передать большую задачу по коду в Codex, Claude Code или OpenCode как фоновому исполнителю, а затем проверять ее ход.
gh-issues
394kПомогает агенту находить задачи GitHub, выбирать, над какими работать, и открывать запросы на слияние с исправлениями, включая ответы на комментарии рецензентов.