본문으로 건너뛰기
Skillpedia
일반 코딩6.4k · #14214

melonjs-scenes-and-state

하는 일

게임 화면을 만들고, 상태 관리자로 화면을 전환하며, 타이머와 트윈을 관리하는 방법을 설명합니다. 게임의 흐름을 구성하는 게임 개발자를 위한 스킬입니다.

사용하는 경우

  • ✓개발자가 플레이 화면으로 이어지는 메뉴 화면을 만들고 싶을 때.
  • ✓개발자의 장면 내용이 화면으로 돌아온 뒤 다시 만들어지지 않을 때.
  • ✓개발자가 게임 오브젝트에 페이드, 펄스, 시간 기반 애니메이션을 넣고 싶을 때.

스킬 링크

https://github.com/melonjs/melonJS/blob/master/packages/melonjs/skills/melonjs-scenes-and-state/SKILL.md

복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.

사용 방법

가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/melonjs/melonJS/blob/master/packages/melonjs/skills/melonjs-scenes-and-state/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

AI에게 요청하는 예시

“제 melonJS 게임에 메뉴 화면과 플레이 화면을 설정하고, 둘을 전환하는 버튼을 넣어 주세요.”

매주 새 스킬 5개. 읽는 데 1분.

작동 방식

스킬은 화면 클래스를 정의하고, reset 핸들러에서 내용을 만든 뒤, 상태 id로 등록하고 나서 그 화면으로 전환하는 방법을 보여 줍니다.

기술 내용 (원본 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

자주 묻는 질문

화면으로 돌아왔을 때 장면 내용이 사라지는 이유는 무엇인가요?

장면 내용은 화면에 들어올 때마다 실행되는 reset 핸들러에 두어야 한다고 스킬은 말합니다.

화면을 전환하는 순서는 어떻게 되나요?

스킬은 먼저 화면을 등록한 다음 그 화면으로 바꾸라고 말합니다.

화면을 바꿀 때 데이터를 보낼 수 있나요?

네. 전환 호출에 전달한 추가 인자는 reset 핸들러로 넘어갑니다.

상세 정보

작성자의 원본 설명

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
업데이트
2026. 11. 2.

이 스킬이 유용한가요?

0

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬