melonjs-scenes-and-state
Что он делает
Навык объясняет, как создавать игровые экраны, переключаться между ними с помощью менеджера состояний и управлять таймерами и твинами. Он нужен разработчикам игр, которые выстраивают ход своей игры.
Когда использовать
- ✓Когда разработчику нужен экран меню, который ведёт к игровому экрану.
- ✓Когда содержимое сцены разработчика не пересоздаётся после возврата на экран.
- ✓Когда разработчику нужна затухающая, пульсирующая или по таймеру анимация игровых объектов.
Ссылка на скилл
https://github.com/melonjs/melonJS/blob/master/packages/melonjs/skills/melonjs-scenes-and-state/SKILL.mdСкопируйте и вставьте её в ваш ИИ (Claude, ChatGPT или Cursor) с просьбой следовать инструкциям.
Как использовать
Самый простой способ: скопируйте сообщение и вставьте его в свой ИИ. Он прочитает скилл и выполнит инструкции.
Готовое сообщение для вставки
Для Claude Code, Codex или Cursor: запустите в папке проекта, и скилл установится.
Скачайте SKILL.md и положите его в папку скиллов вашего агента.
Пример запроса к вашему ИИ
“Настройте экран меню и игровой экран в моей игре на melonJS с кнопкой переключения между ними.”
5 новых скиллов в неделю. 1 минута чтения.
Как это работает
Навык показывает, как определить класс экрана, построить его содержимое в обработчике сброса, зарегистрировать его под идентификатором состояния и затем переключиться на него.
Технический текст (оригинальный SKILL.md)
Оригинальный текст автора на английском, прямо с GitHub.
Scenes, game state and timing
Stages and the state manager
A Stage is a screen. Register it against a state id, then change to it:
import { Stage, state } from "melonjs";
class PlayScreen extends Stage {
onResetEvent(app) { /* build the scene */ }
onDestroyEvent(app) { /* tear it down */ }
}
state.set(state.PLAY, new PlayScreen()); // register first
state.change(state.PLAY); // then switch
Built-in ids: state.LOADING, state.MENU, state.READY, state.PLAY,
state.GAMEOVER (no underscore), state.GAME_END, state.SCORE,
state.CREDITS, state.SETTINGS, state.DEFAULT. state.USER (100) is the
base for your own ids — const CUTSCENE = state.USER + 1.
Build scene content in onResetEvent, not the constructor. onResetEvent
runs on every entry to the state; the constructor runs once. Scene content
created in the constructor exists once and is not rebuilt when you return.
onResetEvent(app) receives the Application — use that rather than importing
the global game.
Extra arguments to state.change are forwarded:
state.change(state.PLAY, false, { level: 2 }); // → onResetEvent(app, { level: 2 })
The second argument is forceChange: pass true to switch immediately instead
of on a deferred tick, which is what you want when changing state right after a
preload completes. It is ignored when a transition is configured — a transition
always drives the switch from its own completion callback.
onResetEvent runs when the switch is made. The first frame, STATE_CHANGE and
a transition's reveal follow once the shaders the stage queued are ready, which
is a few milliseconds once the browser has compiled them before, and at most
1.5s on a first visit. So build the stage in onResetEvent: an object a
STATE_CHANGE listener adds is not waited for, and its first draw may still
compile what it needs. That first frame steps the world once before drawing it,
however short it is, so everything onResetEvent added is in it (the same goes
for the frame after a level.load made while the game runs). Before 20.12 it
was drawn unstepped, and showed the stage's background alone for one frame.
state.change throws Undefined Stage for state '<id>' if nothing was
registered for that id, and state.set throws if the second argument is not a
Stage instance. Neither fails quietly.
Always leave state.LOADING — it is transitional
loader.preload() switches to state.LOADING for you. Building your scene in
the preload callback and then staying there looks like it works, and is one
of the easiest mistakes to make:
// WRONG — the game now runs inside the loading stage, forever
loader.preload(assets, () => {
app.world.addChild(new Player(...));
});
Nothing ever destroys that stage, so the built-in loading screen's logo and progress bar are never removed and sit on top of your game. (Eight of this repository's own examples did this before it was noticed, so it is not an obscure trap.)
Give the scene a stage of its own and switch to it:
class PlayScreen extends Stage {
onResetEvent(app) {
app.world.addChild(new Player(...));
}
}
await loader.preload(assets);
state.set(state.PLAY, new PlayScreen());
state.change(state.PLAY);
The awaited form reads better here than the callback, because "load, then
switch" is exactly what the code then says. If you genuinely want to keep using
the loading stage as your scene, state.change(state.DEFAULT) at least gets
you out of it — but a stage of your own is what you want.
Persistent objects across levels
if (typeof this.HUD === "undefined") {
this.HUD = new Container(); // construct once (or UIBaseElement)
}
this.HUD.isPersistent = true; // survives level changes
this.HUD.floating = true; // screen coordinates, not world
app.world.addChild(this.HUD, 100); // explicit z — see melonjs-renderables
Transitions and pausing
state.transition("fade", "#FFFFFF", 250);
state.transition("mask", "#000", 500, new Ellipse(0, 0, 1, 1)); // shape required
state.transition("pixelate", "#000", 300); // blocks up to 32px; a 4th argument sets the size
state.pause(); // freeze update, keep drawing
state.resume();
app.freeze(150); // brief hit-stop (proxies state.freeze)
state.transition is global and sticky — once set it applies to every later
Частые вопросы
Почему содержимое сцены исчезает после возврата на экран?
Навык говорит, что содержимое сцены должно находиться в обработчике сброса, который выполняется при каждом входе на экран.
В каком порядке переключать экраны?
Навык говорит, что сначала нужно зарегистрировать экран, а затем перейти на него.
Можно ли передавать данные при смене экрана?
Да. Дополнительные аргументы, переданные в вызов смены, передаются в обработчик сброса.
Подробности
Оригинальное описание автора
Use this skill for scene structure and game flow in melonJS — Stage subclasses, the state manager, transitions, pausing, the update loop, timers and tweens. Covers onResetEvent versus the constructor, state.set before state.change, the camera and world lifecycle per stage, and pause-aware timing. Triggers on: Tween, easing, fade out, flash, pulse, punch, shrink back, ease in, ease out, animate over time, countdown in update, Stage, state, state.set, state.change, state.transition, state.pause, onResetEvent, onDestroyEvent, onActivateEvent, onDeactivateEvent, PLAY, MENU, LOADING, update loop, G
repo: melonjs/melonJS
Популярность
- Звёзды на GitHub
- 6.4k
- Место в рейтинге
- #14214
- Лицензия
- 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, выбирать, над какими работать, и открывать запросы на слияние с исправлениями, включая ответы на комментарии рецензентов.