Phaser 4 Core
Set up the foundation of a Phaser game: the Game config, the Scene
lifecycle, asset loading, cameras, and passing data between scenes. Targets
Phaser 4.2 for new projects; keep an existing Phaser 3.90 project on its
pinned major unless the user explicitly asks for a migration.
When to use
- Use when starting a Phaser game, wiring the
Phaser.Game config, structuring
Scenes, loading assets in preload, or fixing scene transitions and shared
state.
- Use when the project has
phaser in package.json or import Phaser from 'phaser',
and code uses preload()/create()/update().
When not to use: movement, velocity, colliders, gravity, or overlap → use
phaser-arcade-physics. Complex rigid-body simulation uses Matter physics (a
separate concern). For cross-engine save/load patterns use save-systems.
Core workflow
- Detect the installed major first. Read
package.json and the lockfile. Use
Phaser 4.2 for new work; do not silently rewrite a Phaser 3 project as Phaser 4.
- Create the game from a config.
new Phaser.Game(config) with type: Phaser.AUTO (WebGL with Canvas fallback), a width/height, and a scene
array. The first scene (and any with active: true) starts automatically.
- Model each screen as a
Scene. Subclass Phaser.Scene, pass a unique
key to super, and implement the lifecycle: init(data) → preload() →
create(data) → update(time, delta).
- Load assets in
preload, use them in create. Queued assets are not
available until create. The loader is per-scene; the cache it fills is global.
- Reset per-run state in
init(), not the constructor. A scene instance is
reused across restarts, so constructor-set fields keep stale values.
- Move between screens with
this.scene.start/launch/switch/sleep/wake.
Share data through this.registry (global) or a sibling scene's event emitter.
- Run and observe. Serve the page, open it, and confirm assets load (watch the
Network tab and console) and scenes switch as expected before assuming success.
Patterns
1. Game config + boot (ES module)
// main.js — one Game owns the renderer, loop, cache, and Scene Manager.
import Phaser from 'phaser';
import BootScene from './scenes/BootScene.js';
import PlayScene from './scenes/PlayScene.js';
const config = {
type: Phaser.AUTO, // WebGL if available, else Canvas
width: 800,
height: 600,
backgroundColor: '#1d1d28',
scale: { mode: Phaser.Scale.FIT, autoCenter: Phaser.Scale.CENTER_BOTH },
scene: [BootScene, PlayScene] // BootScene starts first
};
new Phaser.Game(config);
2. A Scene with the full lifecycle
// scenes/PlayScene.js
import Phaser from 'phaser';
export default class PlayScene extends Phaser.Scene {
constructor() {
super('play'); // unique scene key
}
init(data) {
// Reset run-specific state HERE so restarts start clean.
this.score = 0;
this.level = data.level ?? 1;
}
preload() {
// Queue downloads. Not usable until create().
this.load.image('player', 'assets/player.png');
this.load.spritesheet('coin', 'assets/coin.png', { frameWidth: 16, frameHeight: 16 });
}
create() {
this.player = this.add.sprite(400, 300, 'player');
this.scoreText = this.add.text(10, 10, 'Score: 0', { fontSize: '20px', color: '#fff' });
this.cursors = this.input.keyboard.createCursorKeys();
}
update(time, delta) {
// delta is milliseconds since last frame; divide by 1000 for seconds.
const speed = 200 * (delta / 1000);
if (this.cursors.left.isDown) this.player.x -= speed;
if (this.cursors.right.isDown) this.player.x += speed;
}
}
3. Cross-scene data + events
// The registry is a global DataManager shared by every scene.
this.registry.set('coins', 0); // in any scene
const coins = this.registry.get('coins'); // read anywhere
// React to registry changes (e.g. a HUD scene listening to gameplay):
this.registry.events.on('changedata-coins', (parent, value) => {
this.coinText.setText(`Coins: ${value}`);
});
// Talk directly to another running scene via its event emitter:
const ui = this.scene.get('hud');
ui.events.emit('show-message', 'Level cleared!');
4. Scene transitions (pick the right verb)
this.scene.start('gameover', { score: this.score }); // stop this scene, start target
this.scene.launch('hud'); // run a second scene in parallel (restarts it if already running)
this.scene.run('hud'); // wake if sleeping, resume if paused, else (re)start
this.scene.bringToTop('hud'); // draw order follows the scene list, not launch order
this.scene.switch('menu'); // sleep this scene, start/wake target
this.scene.pause(); // freeze updates but keep rendering (modal)
this.scene.sleep(); // stop updating AND rendering, keep state for wake
5. A camera that follows the player
this.cameras.main.setBounds(0, 0, 1600, 1200); // world size
this.cameras.main.startFollow(this.player, true, 0.1, 0.1); // smooth lerp follow
this.cameras.main.setZoom(1.5);
Pitfalls
- A key works once, then stays down (or Left + Right cancel out) → in Phaser
4.2.1, a
keyup cancelled before the keyboard manager receives it is ignored
because event.defaultPrevented is set. Inspect host-page listeners and browser
extensions before changing movement code. Read the keyboard diagnosis and
capture-phase fallback contract in references/scene-flow.md.
- Assets are
undefined in create/update → you forgot to queue them in
preload, or used the wrong key. The loader runs between preload and create.
- State leaks across a restart → you set fields in the constructor. The Scene
instance is reused; reset run state in
init() and clear arrays on shutdown.
this.scene.start vs this.scene.launch → start stops the calling scene;
launch runs the target alongside it. Using start for a HUD hides the game.
- HUD loses its state or draws behind the game →
launch (and run) on a scene
that is already running shuts it down and starts it again; launch the HUD once, or
guard with if (!this.scene.isActive('hud')). Scenes draw in scene-list order, so a
HUD listed before the gameplay scene renders underneath it until you call
this.scene.bringToTop('hud').
- Scene state read right after
start/launch is stale → scene operations are
queued and run at the start of the next game step, not synchronously.
this is wrong in a callback → arrow functions keep the Scene's this; plain
function callbacks need a context argument or .bind(this).
- Phaser 2 tutorials don't work → "States" were renamed to "Scenes" in Phaser 3,
and each Scene owns its own systems (input, cameras, tweens) rather than a global
Game World.
- Phaser 3 custom pipelines fail in Phaser 4 → Phaser 4 rebuilt the renderer and
replaced the old FX/pipeline extension points. Migrate custom shaders and renderer
plugins against the Phaser 4 guide; do not mechanically copy internal renderer code.
- A Phaser 3 snippet runs but looks wrong in Phaser 4 → common renames:
preFX/
postFX and BitmapMask became filters (obj.enableFilters() then
obj.filters.internal/.external); setPipeline('Light2D') became
setLighting(true); setTintFill(c) only logs an error, so use
setTint(c).setTintMode(Phaser.TintModes.FILL); Phaser.Math.TAU is now 2π (use
Phaser.Math.PI_OVER_2 where v3 code meant π/2); Geom.Point is gone (use
Phaser.Math.Vector2). Canvas rendering still works but is deprecated.
- Pixel art is blurry or shimmers while moving → set
pixelArt: true in the game
config. It turns off antialiasing and turns on roundPixels, which defaults to
false in Phaser 4.
- Nothing renders / black screen → confirm the canvas mounted,
width/height
are set, and a scene actually started (check game.scene.dump() output).
- Two canvases (two games running) after a hot reload or a React/Vue remount →
a second
new Phaser.Game ran while the first was still alive. Keep one instance
and call game.destroy(true) when the host component unmounts; the teardown
finishes on the next frame. Leave noReturn false, or no new game can start on
the page.
References
- For the full scene state machine (pause/resume vs sleep/wake vs stop/start, the
restart-state bug, removing/replacing scenes, and stuck keyboard input), read
references/scene-flow.md.
Related skills
phaser-arcade-physics — velocity, gravity, colliders, overlap, and groups.
input-systems — rebindable, multi-device input architecture (engine-agnostic).
pixijs-rendering / threejs-scene-setup — other browser rendering stacks.
platformer / puzzle — genre templates that compose Phaser skills.
1---2name: phaser-core3description: >4 Set up and debug a Phaser 4 game: the Game config, the Scene lifecycle5 (init/preload/create/update), the asset loader, cameras, and cross-scene6 communication. Use when building or debugging a Phaser game — when the user7 mentions Phaser, Phaser.Game, Phaser.Scene, preload/create/update, this.load,8 this.add, or scene transitions. For Arcade Physics movement/collisions use9 phaser-arcade-physics.10metadata:11 source: https://skillmd.com/skills/junmystery/phaser-core12---1314# Phaser 4 Core1516Set up the foundation of a Phaser game: the `Game` config, the `Scene`17lifecycle, asset loading, cameras, and passing data between scenes. Targets18**Phaser 4.2** for new projects; keep an existing Phaser 3.90 project on its19pinned major unless the user explicitly asks for a migration.2021## When to use2223- Use when starting a Phaser game, wiring the `Phaser.Game` config, structuring24 `Scene`s, loading assets in `preload`, or fixing scene transitions and shared25 state.26- Use when the project has `phaser` in `package.json` or `import Phaser from 'phaser'`,27 and code uses `preload()`/`create()`/`update()`.2829**When *not* to use:** movement, velocity, colliders, gravity, or overlap → use30`phaser-arcade-physics`. Complex rigid-body simulation uses Matter physics (a31separate concern). For cross-engine save/load patterns use `save-systems`.3233## Core workflow34351. **Detect the installed major first.** Read `package.json` and the lockfile. Use36 Phaser 4.2 for new work; do not silently rewrite a Phaser 3 project as Phaser 4.372. **Create the game from a config.** `new Phaser.Game(config)` with `type:38 Phaser.AUTO` (WebGL with Canvas fallback), a `width`/`height`, and a `scene`39 array. The first scene (and any with `active: true`) starts automatically.403. **Model each screen as a `Scene`.** Subclass `Phaser.Scene`, pass a unique41 `key` to `super`, and implement the lifecycle: `init(data)` → `preload()` →42 `create(data)` → `update(time, delta)`.434. **Load assets in `preload`, use them in `create`.** Queued assets are not44 available until `create`. The loader is per-scene; the cache it fills is global.455. **Reset per-run state in `init()`, not the constructor.** A scene instance is46 reused across restarts, so constructor-set fields keep stale values.476. **Move between screens** with `this.scene.start/launch/switch/sleep/wake`.48 Share data through `this.registry` (global) or a sibling scene's event emitter.497. **Run and observe.** Serve the page, open it, and confirm assets load (watch the50 Network tab and console) and scenes switch as expected before assuming success.5152## Patterns5354### 1. Game config + boot (ES module)5556```js57// main.js — one Game owns the renderer, loop, cache, and Scene Manager.58import Phaser from 'phaser';59import BootScene from './scenes/BootScene.js';60import PlayScene from './scenes/PlayScene.js';6162const config = {63 type: Phaser.AUTO, // WebGL if available, else Canvas64 width: 800,65 height: 600,66 backgroundColor: '#1d1d28',67 scale: { mode: Phaser.Scale.FIT, autoCenter: Phaser.Scale.CENTER_BOTH },68 scene: [BootScene, PlayScene] // BootScene starts first69};7071new Phaser.Game(config);72```7374### 2. A Scene with the full lifecycle7576```js77// scenes/PlayScene.js78import Phaser from 'phaser';7980export default class PlayScene extends Phaser.Scene {81 constructor() {82 super('play'); // unique scene key83 }8485 init(data) {86 // Reset run-specific state HERE so restarts start clean.87 this.score = 0;88 this.level = data.level ?? 1;89 }9091 preload() {92 // Queue downloads. Not usable until create().93 this.load.image('player', 'assets/player.png');94 this.load.spritesheet('coin', 'assets/coin.png', { frameWidth: 16, frameHeight: 16 });95 }9697 create() {98 this.player = this.add.sprite(400, 300, 'player');99 this.scoreText = this.add.text(10, 10, 'Score: 0', { fontSize: '20px', color: '#fff' });100 this.cursors = this.input.keyboard.createCursorKeys();101 }102103 update(time, delta) {104 // delta is milliseconds since last frame; divide by 1000 for seconds.105 const speed = 200 * (delta / 1000);106 if (this.cursors.left.isDown) this.player.x -= speed;107 if (this.cursors.right.isDown) this.player.x += speed;108 }109}110```111112### 3. Cross-scene data + events113114```js115// The registry is a global DataManager shared by every scene.116this.registry.set('coins', 0); // in any scene117const coins = this.registry.get('coins'); // read anywhere118119// React to registry changes (e.g. a HUD scene listening to gameplay):120this.registry.events.on('changedata-coins', (parent, value) => {121 this.coinText.setText(`Coins: ${value}`);122});123124// Talk directly to another running scene via its event emitter:125const ui = this.scene.get('hud');126ui.events.emit('show-message', 'Level cleared!');127```128129### 4. Scene transitions (pick the right verb)130131```js132this.scene.start('gameover', { score: this.score }); // stop this scene, start target133this.scene.launch('hud'); // run a second scene in parallel (restarts it if already running)134this.scene.run('hud'); // wake if sleeping, resume if paused, else (re)start135this.scene.bringToTop('hud'); // draw order follows the scene list, not launch order136this.scene.switch('menu'); // sleep this scene, start/wake target137this.scene.pause(); // freeze updates but keep rendering (modal)138this.scene.sleep(); // stop updating AND rendering, keep state for wake139```140141### 5. A camera that follows the player142143```js144this.cameras.main.setBounds(0, 0, 1600, 1200); // world size145this.cameras.main.startFollow(this.player, true, 0.1, 0.1); // smooth lerp follow146this.cameras.main.setZoom(1.5);147```148149## Pitfalls150151- **A key works once, then stays down (or Left + Right cancel out)** → in Phaser152 4.2.1, a `keyup` cancelled before the keyboard manager receives it is ignored153 because `event.defaultPrevented` is set. Inspect host-page listeners and browser154 extensions before changing movement code. Read the keyboard diagnosis and155 capture-phase fallback contract in `references/scene-flow.md`.156- **Assets are `undefined` in `create`/`update`** → you forgot to queue them in157 `preload`, or used the wrong key. The loader runs between `preload` and `create`.158- **State leaks across a restart** → you set fields in the constructor. The Scene159 instance is reused; reset run state in `init()` and clear arrays on `shutdown`.160- **`this.scene.start` vs `this.scene.launch`** → `start` stops the calling scene;161 `launch` runs the target alongside it. Using `start` for a HUD hides the game.162- **HUD loses its state or draws behind the game** → `launch` (and `run`) on a scene163 that is already running shuts it down and starts it again; launch the HUD once, or164 guard with `if (!this.scene.isActive('hud'))`. Scenes draw in scene-list order, so a165 HUD listed before the gameplay scene renders underneath it until you call166 `this.scene.bringToTop('hud')`.167- **Scene state read right after `start`/`launch` is stale** → scene operations are168 queued and run at the start of the next game step, not synchronously.169- **`this` is wrong in a callback** → arrow functions keep the Scene's `this`; plain170 `function` callbacks need a context argument or `.bind(this)`.171- **Phaser 2 tutorials don't work** → "States" were renamed to "Scenes" in Phaser 3,172 and each Scene owns its own systems (input, cameras, tweens) rather than a global173 Game World.174- **Phaser 3 custom pipelines fail in Phaser 4** → Phaser 4 rebuilt the renderer and175 replaced the old FX/pipeline extension points. Migrate custom shaders and renderer176 plugins against the Phaser 4 guide; do not mechanically copy internal renderer code.177- **A Phaser 3 snippet runs but looks wrong in Phaser 4** → common renames: `preFX`/178 `postFX` and `BitmapMask` became filters (`obj.enableFilters()` then179 `obj.filters.internal`/`.external`); `setPipeline('Light2D')` became180 `setLighting(true)`; `setTintFill(c)` only logs an error, so use181 `setTint(c).setTintMode(Phaser.TintModes.FILL)`; `Phaser.Math.TAU` is now 2π (use182 `Phaser.Math.PI_OVER_2` where v3 code meant π/2); `Geom.Point` is gone (use183 `Phaser.Math.Vector2`). Canvas rendering still works but is deprecated.184- **Pixel art is blurry or shimmers while moving** → set `pixelArt: true` in the game185 config. It turns off antialiasing and turns on `roundPixels`, which defaults to186 `false` in Phaser 4.187- **Nothing renders / black screen** → confirm the canvas mounted, `width`/`height`188 are set, and a scene actually started (check `game.scene.dump()` output).189- **Two canvases (two games running) after a hot reload or a React/Vue remount** →190 a second `new Phaser.Game` ran while the first was still alive. Keep one instance191 and call `game.destroy(true)` when the host component unmounts; the teardown192 finishes on the next frame. Leave `noReturn` false, or no new game can start on193 the page.194195## References196197- For the full scene state machine (pause/resume vs sleep/wake vs stop/start, the198 restart-state bug, removing/replacing scenes, and stuck keyboard input), read199 `references/scene-flow.md`.200201## Related skills202203- `phaser-arcade-physics` — velocity, gravity, colliders, overlap, and groups.204- `input-systems` — rebindable, multi-device input architecture (engine-agnostic).205- `pixijs-rendering` / `threejs-scene-setup` — other browser rendering stacks.206- `platformer` / `puzzle` — genre templates that compose Phaser skills.