Scene Manager
A stack of scenes (title, play, pause, game over) with enter, exit, pause and resume steps, and fade transitions between them.
Files: scene-manager.js (the component, no dependencies) and scene-manager.test.mjs (6 tests).
Copy scene-manager.js into your game, for example to src/components/, and import it as an ES module.
Usage
import { createScenes } from "./scene-manager.js";
const scenes = createScenes();
scenes.add("title", { enter() {}, update(dt) { if (input.pressed("start")) scenes.go("play", { level: 1 }, { fade: 0.4 }); }, draw(ctx) {} });
scenes.add("play", (params) => new PlayScene(params)); // a factory makes a fresh scene each time
scenes.add("pause", { overlay: true, update() { if (input.pressed("pause")) scenes.pop(); }, draw(ctx) {} });
scenes.go("title");
function frame(dt) { scenes.update(dt); scenes.draw(ctx); }
API
createScenes() → scenesscenes.add(name, sceneObjectOrFactory)scenes.go(name, params, { fade })replace the whole stack (fade = seconds, out then in)scenes.push(name, params)put a scene on top (pause menu); the one below gets pause()scenes.pop(result)remove the top scene; the one below gets resume(result)scenes.update(dt)updates the top scene only (and those below it with updateBelow: true)scenes.draw(ctx)draws from the highest non-overlay scene up, so overlays show the game behind themscenes.fade0..1 cover amount during a transition (also drawn as black by draw() unless drawFade: false)scenes.current / scenes.name / scenes.stackscenes.onChange(fn)fn(name, previousName)
Scene methods (all optional): enter(params), exit(), pause(), resume(result), update(dt), draw(ctx). Flags: overlay, updateBelow.
Changes asked for during update() happen after it finishes, so a scene never runs after it was removed.
Engines
| Engine | Notes |
|---|---|
| Vanilla, PixiJS, Three.js | yes. With Pixi or Three, draw(ctx) is unused; show and hide containers in enter() and exit(). |
| Phaser | use Phaser’s own scenes instead; this one fits games that have no scene system. |
Tests
Node tests: lifecycle order, push and pop with results, overlays drawing, factories, deferred changes during update, fades.
Run them with node --test toolkit/components/scene-manager/ (Node 20 or newer, nothing to install).