
Phaser
- 839 installs
- 305 repo stars
- Updated May 25, 2026
- opusgamelabs/game-creator
phaser is a game-development skill that teaches high-performance Phaser 3 TypeScript patterns—including texture atlas loading and draw-call optimization—for developers building 2D HTML5 browser games.
About
phaser is a skill in opusgamelabs/game-creator documenting production Phaser 3 patterns for 2D HTML5 games. It mandates packing sprites into atlases via TexturePacker or free-tex-packer exported as JSON Hash instead of loading individual PNGs that cost one draw call each. TypeScript examples show this.load.atlas and frame-based this.add.sprite calls using atlas frame IDs. Guidance contrasts bad per-image loads with single-atlas approaches that batch rendering. Developers reach for phaser when implementing Phaser 3 gameplay, optimizing WebGL draw calls, or standardizing asset pipeline conventions across a browser game codebase.
- Texture atlas best practices that reduce draw calls from many individual images to one atlas
- Atlas animation creation using generateFrameNames with prefix/start/end/zeroPad
- Object pooling implementation with Phaser Groups and maxSize for frequent spawn/destroy cycles
- Concrete before-and-after code examples for sprites, enemies, coins and collectibles
- Performance checklist covering atlases, pooling, and animation frame management
Phaser by the numbers
- 839 all-time installs (skills.sh)
- +29 installs in the week ending Aug 4, 2026 (Skillselion tracking)
- Ranked #28 of 247 Game Development skills by installs in the Skillselion catalog
- Security screen: LOW risk (skills.sh audit)
- Data as of Aug 4, 2026 (Skillselion catalog sync)
npx skills add https://github.com/opusgamelabs/game-creator --skill phaserAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 839 |
|---|---|
| repo stars | ★ 305 |
| Security audit | 3 / 3 scanners passed |
| Last updated | May 25, 2026 |
| Repository | opusgamelabs/game-creator ↗ |
How do you optimize Phaser 3 sprite draw calls?
Generate high-performance Phaser 3 code patterns for 2D HTML5 games.
Who is it for?
Game developers building Phaser 3 2D HTML5 games who need atlas-based asset loading and performance conventions.
Skip if: Unity or Godot projects, 3D WebGL engines, or teams not using Phaser 3 with TypeScript asset pipelines.
When should I use this skill?
A developer writes Phaser 3 game code involving sprite loading, texture atlases, or draw-call performance tuning.
What you get
Phaser 3 TypeScript code using JSON Hash texture atlases and frame-based sprite instantiation patterns.
- Phaser 3 TypeScript gameplay code
- Atlas loading configuration
By the numbers
- Contrasts 3 separate image loads vs 1 atlas load in examples
- Targets Phaser 3 with JSON Hash atlas export format
Files
Phaser 3 Game Development
You are an expert Phaser game developer building games with the game-creator plugin. Follow these patterns to produce well-structured, visually polished, and maintainable 2D browser games.
Core Principles
1. Core loop first — Implement the minimum gameplay loop before any polish: boot → preload → create → update. Add the win/lose condition and scoring before visuals, audio, or juice. Keep initial scope small: 1 scene, 1 mechanic, 1 fail condition. Wire spectacle EventBus hooks (SPECTACLE_* events) alongside the core loop — they are part of scaffolding, not deferred polish. 2. TypeScript-first — Always use TypeScript for type safety and IDE support 3. Scene-based architecture — Each game screen is a Scene; keep them focused 4. Vite bundling — Use the official phaserjs/template-vite-ts template 5. Composition over inheritance — Prefer composing behaviors over deep class hierarchies 6. Data-driven design — Define levels, enemies, and configs in JSON/data files 7. Event-driven communication — All cross-scene/system communication via EventBus 8. Restart-safe — Gameplay must be fully restart-safe and deterministic. GameState.reset() must restore a clean slate. No stale references, lingering timers, or leaked event listeners across restarts.
Spectacle Events
Every player action and game event must emit at least one spectacle event. These hooks exist in the template EventBus — the design pass attaches visual effects to them.
| Event | Constant | When to Emit |
|---|---|---|
spectacle:entrance | SPECTACLE_ENTRANCE | In create() when the player/entities first appear on screen |
spectacle:action | SPECTACLE_ACTION | On every player input (tap, jump, shoot, swipe) |
spectacle:hit | SPECTACLE_HIT | When player hits/destroys an enemy, collects an item, or scores |
spectacle:combo | SPECTACLE_COMBO | When consecutive hits/scores happen without a miss. Pass { combo: n } |
spectacle:streak | SPECTACLE_STREAK | When combo reaches milestones (5, 10, 25, 50). Pass { streak: n } |
spectacle:near_miss | SPECTACLE_NEAR_MISS | When player narrowly avoids danger (within ~20% of collision radius) |
Rule: If a gameplay moment has no spectacle event, add one. The design pass cannot polish what it cannot hook into.
Mandatory Conventions
All games MUST follow the game-creator conventions:
- `core/` directory with EventBus, GameState, and Constants
- EventBus singleton —
domain:actionevent naming, no direct scene references - GameState singleton — Centralized state with
reset()for clean restarts - Constants file — Every magic number, color, speed, and config value — zero hardcoded values
- Scene cleanup — Remove EventBus listeners in
shutdown()
See conventions.md for full details and code examples.
Project Setup
Use the official Vite + TypeScript template as your starting point:
npx degit phaserjs/template-vite-ts my-game
cd my-game && npm installRequired Directory Structure
src/
├── core/
│ ├── EventBus.ts # Singleton event bus + event constants
│ ├── GameState.ts # Centralized state with reset()
│ └── Constants.ts # ALL config values
├── scenes/
│ ├── Boot.ts # Minimal setup, start Game scene
│ ├── Preloader.ts # Load all assets, show progress bar
│ ├── Game.ts # Main gameplay (starts immediately, no title screen)
│ └── GameOver.ts # End screen with restart
├── objects/ # Game entities (Player, Enemy, etc.)
├── systems/ # Managers and subsystems
├── ui/ # UI components (buttons, bars, dialogs)
├── audio/ # Audio manager, music, SFX
├── config.ts # Phaser.Types.Core.GameConfig
└── main.ts # Entry pointSee project-setup.md for full config and tooling details.
Scene Architecture
- Lifecycle:
init()→preload()→create()→update(time, delta) - Use
init()for receiving data from scene transitions - Load assets in a dedicated
Preloaderscene, not in every scene - Keep
update()lean — delegate to subsystems and game objects - No title screen by default — boot directly into gameplay. Only add a title/menu scene if the user explicitly asks for one
- No in-game score HUD — the Play.fun widget displays score in a deadzone at the top of the game. Do not create a separate UIScene or HUD overlay for score display
- Use parallel scenes for UI overlays (pause menu) only when requested
Play.fun Safe Zone
When games run inside the Play.fun dashboard on mobile Safari, the SDK sets CSS custom properties on the game iframe's document.documentElement:
--ogp-safe-top-inset— space below the Play.fun header bubbles (~68px on mobile)--ogp-safe-bottom-inset— space above Safari bottom controls (~148px on mobile)
Both default to 0px when not running inside the dashboard (desktop, standalone).
The template's Constants.js reads these at boot and exposes SAFE_ZONE.TOP and SAFE_ZONE.BOTTOM in canvas pixels (CSS value × DPR). A static fallback (GAME.HEIGHT * 0.08) ensures the top safe zone works even without the SDK.
Rules:
- All UI text, buttons, and HUD elements must be positioned below
SAFE_ZONE.TOPand aboveGAME.HEIGHT - SAFE_ZONE.BOTTOM - Gameplay entities should not spawn in the safe zone areas
- The game-over screen, score panels, and restart buttons must offset from both
SAFE_ZONE.TOPandSAFE_ZONE.BOTTOM - Use
const usableH = GAME.HEIGHT - SAFE_ZONE.TOP - SAFE_ZONE.BOTTOMfor calculating proportional positions in UI scenes - Game canvas and backgrounds should fill the full viewport (bleed behind browser chrome)
- Touch controls at the bottom must account for
SAFE_ZONE.BOTTOM
import { SAFE_ZONE } from '../core/Constants.js';
// In any UI scene:
const safeTop = SAFE_ZONE.TOP;
const safeBottom = SAFE_ZONE.BOTTOM;
const usableH = GAME.HEIGHT - safeTop - safeBottom;
const title = this.add.text(cx, safeTop + usableH * 0.15, 'GAME OVER', { ... });
const button = createButton(scene, cx, safeTop + usableH * 0.6, 'PLAY AGAIN', callback);
// Touch controls / bottom HUD:
const bottomY = GAME.HEIGHT - safeBottom - 40 * PX;How it works in Constants.js:
function _readSafeInsets() {
const s = getComputedStyle(document.documentElement);
const top = parseInt(s.getPropertyValue('--ogp-safe-top-inset')) || 0;
const bottom = parseInt(s.getPropertyValue('--ogp-safe-bottom-inset')) || 0;
return { top: top * DPR, bottom: bottom * DPR };
}
const _insets = _readSafeInsets();
export const SAFE_ZONE = {
TOP: Math.max(GAME.HEIGHT * 0.08, _insets.top),
BOTTOM: _insets.bottom,
LEFT: 0,
RIGHT: 0,
};- Communicate between scenes via EventBus (not direct references)
See scenes-and-lifecycle.md for patterns and examples.
Game Objects
- Extend
Phaser.GameObjects.Sprite(or other base classes) for custom objects - Use
Phaser.GameObjects.Groupfor object pooling (bullets, coins, enemies) - Use
Phaser.GameObjects.Containerfor composite objects, but avoid deep nesting - Register custom objects with
GameObjectFactoryfor scene-level access
See game-objects.md for implementation patterns.
Physics
- Arcade Physics — Use for simple games (platformers, top-down). Fast and lightweight.
- Matter.js — Use when you need realistic collisions, constraints, or complex shapes.
- Never mix physics engines in the same game.
- Use the state pattern for character movement (idle, walk, jump, attack).
See physics-and-movement.md for details.
Performance (Critical Rules)
- Use texture atlases — Pack sprites into atlases, never load individual images at scale
- Object pooling — Use Groups with
maxSize; recycle withsetActive(false)/setVisible(false) - Minimize update work — Only iterate active objects; use
getChildren().filter(c => c.active) - Camera culling — Enable for large worlds; off-screen objects skip rendering
- Batch rendering — Fewer unique textures per frame = better draw call batching
- Mobile — Reduce particle counts, simplify physics, consider 30fps target
- `pixelArt: true` — Enable in game config for pixel art games (nearest-neighbor scaling)
See assets-and-performance.md for full optimization guide.
Advanced Patterns
- ECS with bitECS — Entity Component System for data-oriented design (used internally by Phaser 4)
- State machines — Manage entity behavior states cleanly
- Singleton managers — Cross-scene services (audio, save data, analytics)
- Event bus — Decouple systems with a shared EventEmitter
- Tiled integration — Use Tiled map editor for level design
See patterns.md for implementations.
Mobile Input Strategy (60/40 Rule)
All games MUST work on desktop AND mobile unless explicitly specified otherwise. Focus 60% mobile / 40% desktop for tradeoffs. Pick the best mobile input for each game concept:
| Game Type | Primary Mobile Input | Desktop Input |
|---|---|---|
| Platformer | Tap left/right half + tap-to-jump | Arrow keys / WASD |
| Runner/endless | Tap / swipe up to jump | Space / Up arrow |
| Puzzle/match | Tap targets (44px min) | Click |
| Shooter | Virtual joystick + tap-to-fire | Mouse + WASD |
| Top-down | Virtual joystick | Arrow keys / WASD |
Implementation Pattern
Abstract input into an inputState object so game logic is source-agnostic:
// In Scene update():
const isMobile = this.sys.game.device.os.android ||
this.sys.game.device.os.iOS || this.sys.game.device.os.iPad;
let left = false, right = false, jump = false;
// Keyboard
left = this.cursors.left.isDown || this.wasd.left.isDown;
right = this.cursors.right.isDown || this.wasd.right.isDown;
jump = Phaser.Input.Keyboard.JustDown(this.spaceKey);
// Touch (merge with keyboard)
if (isMobile) {
// Left half tap = left, right half = right, or use tap zones
this.input.on('pointerdown', (p) => {
if (p.x < this.scale.width / 2) left = true;
else right = true;
});
}
this.player.update({ left, right, jump });Responsive Canvas Config (Retina/High-DPI)
See project-setup.md for the full responsive canvas config, entity sizing, HTML boilerplate, and portrait-first game patterns.
Visible Touch Controls
Always show visual touch indicators on touch-capable devices — never rely on invisible tap zones. Use capability detection (not OS-based detection) to determine touch support:
// Good — detects touch laptops, tablets, 2-in-1s
const hasTouch = ('ontouchstart' in window) || (navigator.maxTouchPoints > 0);
// Bad — misses touch-screen laptops, iPadOS (reports as desktop)
const isMobile = device.os.android || device.os.iOS;Render semi-transparent arrow buttons (or direction indicators) at the bottom of the screen. Use TOUCH constants from Constants.js for sizing (12% of canvas width), alpha (0.35 idle / 0.6 active), and margins. Update alpha in the update() loop based on input state for visual feedback.
Enable pointer input (pointerdown, pointermove, pointerup) on all devices — pointer events work for both mouse and touch. This eliminates the need for separate mobile/desktop input code paths.
Minimum Entity Sizes for Mobile
Collectibles, hazards, and interactive items must be at least 7–8% of `GAME.WIDTH` to be recognizable on phone screens. Smaller entities become indistinguishable blobs on mobile.
// Good — recognizable on mobile
ATTACK_WIDTH: _canvasW * 0.09,
POWERUP_WIDTH: _canvasW * 0.072,
// Bad — too small on phone screens
ATTACK_WIDTH: _canvasW * 0.04,
POWERUP_WIDTH: _canvasW * 0.035,For the main player character, use 12–15% of GAME.WIDTH (see Entity Sizing above).
Button Pattern (Container + Graphics + Text)
See game-objects.md for the full button implementation pattern (Container + Graphics + Text with hover/press states) and the list of broken patterns to avoid.
Anti-Patterns (Avoid These)
- Bloated `update()` methods — Don't put all game logic in one giant update with nested conditionals. Delegate to objects and systems.
- Overwriting Scene injection map properties — Never name your properties
world,input,cameras,add,make,scene,sys,game,cache,registry,sound,textures,events,physics,matter,time,tweens,lights,data,load,anims,renderer, orplugins. These are reserved by Phaser. - Creating objects in `update()` without pooling — This causes GC spikes. Always pool frequently created/destroyed objects. Avoid expensive per-frame allocations — reuse objects, arrays, and temporary variables.
- Loading individual sprites instead of atlases — Each separate texture is a draw call. Pack them.
- Tightly coupling scenes — Don't store direct references between scenes. Use EventBus.
- Ignoring `delta` in update — Always use
deltafor time-based movement, not frame-based. - Deep container nesting — Containers disable render batching for children. Keep hierarchy flat.
- Not cleaning up — Remove event listeners and timers in
shutdown()to prevent memory leaks. This is critical for restart-safety — stale listeners cause double-firing and ghost behavior after restart. - Hardcoded values — Every number belongs in
Constants.ts. No magic numbers in game logic. - Unwired physics colliders — Creating a static body with
physics.add.existing(obj, true)does nothing on its own. You MUST callphysics.add.collider(bodyA, bodyB, callback)to connect two bodies. Every static collider (ground, walls, platforms) needs an explicit collider or overlap call wiring it to the entities that should interact with it. - Invisible or hidden button elements — Never set
setAlpha(0)on an interactive game object and layer Graphics or other display objects on top. For buttons, always use the Container + Graphics + Text pattern (see game-objects.md). Common broken patterns: (1) Drawing a Graphics rect after adding Text, hiding the label behind it. (2) Creating a Zone for hit area with Graphics drawn over it, making the Zone unreachable. (3) Making Text interactive but covering it with a Graphics background drawn afterward. The fix is always: Container first, Graphics added to container, Text added to container (in that order), Container is the interactive element. - No mute toggle — See the
mute-buttonrule. Games with audio must have a mute toggle.
Examples
- Simple Game — Minimal complete Phaser game (collector game)
- Complex Game — Multi-scene game with state machines, pooling, EventBus, and all conventions
Pre-Ship Validation Checklist
Before considering a game complete, verify:
- [ ] Core loop works — Player can start, play, lose/win, and see the result
- [ ] Restart works cleanly —
GameState.reset()restores a clean slate, no stale listeners or timers - [ ] Touch + keyboard input — Game works on mobile (tap/swipe) and desktop (keyboard/mouse)
- [ ] Responsive canvas —
Scale.FIT+CENTER_BOTH+zoom: 1/DPRwith DPR-multiplied dimensions, crisp on Retina - [ ] All values in Constants — Zero hardcoded magic numbers in game logic
- [ ] EventBus only — No direct cross-scene/module imports for communication
- [ ] Scene cleanup — All EventBus listeners removed in
shutdown() - [ ] Physics wired — Every static body has an explicit
collider()oroverlap()call - [ ] Object pooling — Frequently created/destroyed objects use Groups with
maxSize - [ ] Delta-based movement — All motion uses
delta, not frame count - [ ] Mute toggle — See
mute-buttonrule - [ ] Spectacle hooks wired — Every player action and game event emits a
SPECTACLE_*event; entrance sequence fires increate() - [ ] Build passes —
npm run buildsucceeds with no errors - [ ] No console errors — Game runs without uncaught exceptions or WebGL failures
Reference Files
| File | Topic |
|---|---|
| conventions.md | Mandatory game-creator architecture conventions |
| project-setup.md | Scaffolding, Vite, TypeScript config, responsive canvas, entity sizing, portrait mode |
| scenes-and-lifecycle.md | Scene system deep dive |
| game-objects.md | Custom objects, groups, containers, button pattern |
| physics-and-movement.md | Physics engines, movement patterns |
| assets-and-performance.md | Assets, optimization, mobile |
| patterns.md | ECS, state machines, singletons |
| no-asset-design.md | Procedural visuals: gradients, parallax, particles, juice |
Assets & Performance
Texture Atlases
Always pack sprites into atlases instead of loading individual images:
// Bad: individual images (one draw call each)
this.load.image('player', 'assets/player.png');
this.load.image('enemy', 'assets/enemy.png');
this.load.image('coin', 'assets/coin.png');
// Good: single atlas (one draw call for all)
this.load.atlas('sprites', 'assets/atlases/sprites.png', 'assets/atlases/sprites.json');Create atlases with TexturePacker or free-tex-packer. Export as JSON Hash format.
// Using atlas frames
this.add.image(100, 100, 'sprites', 'player-idle');
this.add.sprite(200, 200, 'sprites', 'enemy-walk-01');Atlas Animations
// In Preloader or Boot scene
this.anims.create({
key: 'player-walk',
frames: this.anims.generateFrameNames('sprites', {
prefix: 'player-walk-',
start: 1,
end: 8,
zeroPad: 2,
}),
frameRate: 12,
repeat: -1,
});Object Pooling
Use Groups for anything created/destroyed frequently:
const coins = this.physics.add.group({
classType: Coin,
maxSize: 20,
runChildUpdate: true,
});
// Spawn
function spawnCoin(x: number, y: number) {
const coin = coins.getFirstDead(false) as Coin | null;
if (coin) {
coin.activate(x, y);
}
}
// Return to pool
function collectCoin(coin: Coin) {
coin.setActive(false);
coin.setVisible(false);
coin.body!.enable = false;
}Update Loop Optimization
// Bad: iterating all children
update() {
this.enemies.getChildren().forEach(enemy => {
(enemy as Enemy).update();
});
}
// Good: only update active children
update() {
this.enemies.getChildren()
.filter(e => e.active)
.forEach(enemy => (enemy as Enemy).update());
}
// Best: use runChildUpdate on the group and let Phaser handle it
// (automatically skips inactive children)Camera Culling
For large worlds, objects off-screen still render by default. Phaser automatically culls objects outside camera bounds for most game objects, but ensure it's working:
// Set world bounds larger than camera
this.physics.world.setBounds(0, 0, 3200, 600);
this.cameras.main.setBounds(0, 0, 3200, 600);
this.cameras.main.startFollow(this.player, true, 0.1, 0.1);Audio Best Practices
- Load
.oggwith.mp3fallback:this.load.audio('sfx', ['sfx.ogg', 'sfx.mp3']) - Use
this.sound.play('sfx', { volume: 0.5 })for one-shots - Use
this.sound.add('bgm', { loop: true })for music - Audio won't play until user interacts with the page (browser policy). Phaser handles this with its audio unlock system.
BitmapText for Performance
Phaser.GameObjects.Text creates a canvas texture per instance. For frequently updated text (score, timers), use BitmapText:
// In preload
this.load.bitmapFont('pixelfont', 'assets/fonts/pixel.png', 'assets/fonts/pixel.xml');
// In create
const score = this.add.bitmapText(16, 16, 'pixelfont', 'Score: 0', 24);Mobile Optimization (Primary Target)
Mobile is the primary deployment target. Design for mobile first, then verify desktop.
- Target 30fps if needed:
fps: { target: 30, forceSetTimeOut: true }in game config - Reduce particle counts by 50-75%
- Use simpler physics bodies (circles over polygons)
- Minimize texture swaps — pack everything into fewer atlases
- Use
Phaser.Scale.FITwithautoCenterfor responsive sizing - Touch target sizes: All interactive elements (buttons, game objects the player taps) must be at least 44x44px on screen. Smaller targets frustrate mobile players.
- Test on real devices, not just browser DevTools throttling
Memory Management
- Remove event listeners in
shutdown():
this.events.on('shutdown', () => {
this.game.events.off('custom-event', this.handler, this);
this.registry.events.off('changedata-score', this.onScore, this);
});- Destroy objects you no longer need:
sprite.destroy() - Clear Groups:
group.clear(true, true)(removes from scene and destroys) - For scene restarts, Phaser automatically cleans up objects created via
this.add.*
Loading Screen
export class Preloader extends Phaser.Scene {
preload() {
const width = this.cameras.main.width;
const height = this.cameras.main.height;
const progressBar = this.add.rectangle(width / 2, height / 2, 0, 30, 0xffffff);
const progressBox = this.add.rectangle(width / 2, height / 2, 320, 30).setStrokeStyle(2, 0xffffff);
this.load.on('progress', (value: number) => {
progressBar.width = 300 * value;
});
this.load.on('complete', () => {
progressBar.destroy();
progressBox.destroy();
});
// Load all game assets here...
}
}Game-Creator Conventions
These conventions are mandatory for all games built with the game-creator plugin. They ensure consistent architecture, clean restarts, and maintainability — especially important for beginners.
Directory Structure
Every game MUST use a core/ directory for foundational modules:
src/
├── core/
│ ├── EventBus.ts # Singleton event bus (see below)
│ ├── GameState.ts # Centralized state with reset()
│ └── Constants.ts # ALL config values — zero hardcoded numbers
├── scenes/
│ ├── Boot.ts # Minimal setup, start Game scene
│ ├── Preloader.ts # Load all assets, show progress bar
│ ├── Game.ts # Main gameplay (starts immediately, no title screen)
│ └── GameOver.ts # End screen with restart
├── objects/ # Game entities (Player, Enemy, etc.)
├── systems/ # Managers and subsystems
├── ui/ # UI components (buttons, bars, dialogs)
├── audio/ # Audio manager, music patterns, SFX
├── config.ts # Phaser.Types.Core.GameConfig
└── main.ts # Entry point1. EventBus Singleton (Non-Negotiable)
All cross-scene and cross-system communication goes through a single EventBus. Scenes and systems never import or reference each other directly.
// src/core/EventBus.ts
import Phaser from 'phaser';
export const EventBus = new Phaser.Events.EventEmitter();
// Event name constants — use domain:action naming
export const Events = {
// Player domain
PLAYER_JUMP: 'player:jump',
PLAYER_DIED: 'player:died',
PLAYER_DAMAGED: 'player:damaged',
// Score domain
SCORE_CHANGED: 'score:changed',
// Game domain
GAME_START: 'game:start',
GAME_OVER: 'game:over',
GAME_RESTART: 'game:restart',
// Audio domain
AUDIO_INIT: 'audio:init',
MUSIC_PLAY: 'music:play',
MUSIC_STOP: 'music:stop',
SFX_PLAY: 'sfx:play',
} as const;Rules:
- Event names use
domain:actionformat (e.g.,player:died,score:changed) - Define all events as constants in
Events— never use string literals - Always clean up listeners in scene
shutdown()
// Usage
import { EventBus, Events } from '../core/EventBus';
// Subscribe (store reference for cleanup)
const handler = (data: { score: number }) => { /* ... */ };
EventBus.on(Events.SCORE_CHANGED, handler, this);
// Emit
EventBus.emit(Events.SCORE_CHANGED, { score: 100 });
// Cleanup in shutdown
EventBus.off(Events.SCORE_CHANGED, handler, this);2. GameState Singleton (Non-Negotiable)
A single centralized state object. Systems read from it. Events trigger mutations. Must have reset() for clean restarts.
// src/core/GameState.ts
import { PLAYER, GAME_DEFAULTS } from './Constants';
class GameState {
// Player state
score = 0;
bestScore = 0;
health = PLAYER.MAX_HEALTH;
lives = PLAYER.STARTING_LIVES;
// Game state
started = false;
paused = false;
gameOver = false;
level = 1;
reset() {
this.score = 0;
this.health = PLAYER.MAX_HEALTH;
this.lives = PLAYER.STARTING_LIVES;
this.started = false;
this.paused = false;
this.gameOver = false;
this.level = 1;
// Note: bestScore persists across resets
}
}
export const gameState = new GameState();Rules:
- One instance, exported as a singleton
reset()restores defaults for a clean restart (preserve high scores / persistent data)- State values come from Constants — no hardcoded defaults
- Systems read state directly but mutate via methods or events
3. Constants File (Non-Negotiable)
Every magic number, color, timing, speed, size, and config value lives here. Zero hardcoded values in game logic.
// src/core/Constants.ts
// Game canvas
export const GAME = {
WIDTH: 800,
HEIGHT: 600,
GRAVITY: 300,
BACKGROUND_COLOR: '#1a1a2e',
};
// Player tuning
export const PLAYER = {
SPEED: 200,
JUMP_FORCE: -450,
MAX_HEALTH: 100,
STARTING_LIVES: 3,
INVULNERABLE_MS: 500,
SPRITE_KEY: 'player',
};
// Enemy tuning
export const ENEMY = {
SPEED: 80,
POOL_SIZE: 10,
SCORE_VALUE: 100,
SPRITE_KEY: 'enemy',
};
// UI
export const UI = {
FONT_SIZE: '24px',
FONT_COLOR: '#ffffff',
PADDING: 16,
};
// Colors (hex numbers for Phaser tints/fills)
export const COLORS = {
DAMAGE_TINT: 0xff0000,
PLATFORM: 0x4a4a4a,
HEALTH_BAR: 0x00ff00,
HEALTH_BG: 0x333333,
};Rules:
- Group by domain (PLAYER, ENEMY, GAME, UI, COLORS, AUDIO, etc.)
- Use SCREAMING_SNAKE for values, PascalCase for group names
- When tuning gameplay, you change ONE file — never hunt through game logic
4. When Adding Features (Checklist)
Follow this order every time you add a feature:
1. Constants — Add config values to Constants.ts 2. Events — Define new events in EventBus.ts using domain:action naming 3. State — Add fields to GameState.ts if the feature has persistent state 4. Entity / System — Create the implementation in objects/ or systems/ 5. Scene wiring — Connect it in the appropriate Scene 6. Communication — Talk to other systems ONLY through EventBus
Never skip steps 1-3. They keep the architecture clean as the game grows.
5. Scene Cleanup (Non-Negotiable)
Every scene that subscribes to EventBus events MUST clean up in shutdown():
export class Game extends Phaser.Scene {
create() {
EventBus.on(Events.PLAYER_DIED, this.onPlayerDied, this);
this.events.on('shutdown', this.cleanup, this);
}
private cleanup() {
EventBus.off(Events.PLAYER_DIED, this.onPlayerDied, this);
}
}Failing to clean up causes duplicate listeners on scene restart — a common source of bugs.
6. Restart Flow
Games must support clean restarts without page reload:
// In GameOver scene
this.input.once('pointerdown', () => {
gameState.reset(); // Clean state
EventBus.emit(Events.GAME_RESTART); // Notify systems (audio, etc.)
this.scene.start('Game'); // Restart
});The gameState.reset() + EventBus notification pattern ensures all systems return to a clean state.
Complex Game Example — Platformer with Advanced Patterns
A multi-scene platformer demonstrating state machines, object pooling, event bus, centralized state, and data-driven design — following all game-creator conventions.
Architecture
src/
├── core/
│ ├── EventBus.ts
│ ├── GameState.ts
│ └── Constants.ts
├── scenes/
│ ├── Boot.ts
│ ├── Preloader.ts
│ ├── Game.ts
│ ├── HUD.ts
│ └── GameOver.ts
├── objects/
│ ├── Player.ts
│ └── EnemyGroup.ts
├── systems/
│ └── StateMachine.ts
├── config.ts
└── main.tssrc/core/Constants.ts
// Every tunable value lives here — zero hardcoded numbers in game logic
export const GAME = {
WIDTH: 800,
HEIGHT: 600,
GRAVITY: 300,
WORLD_WIDTH: 1600,
BACKGROUND_COLOR: '#1a1a2e',
};
export const PLAYER = {
SPEED: 200,
JUMP_FORCE: 450,
AIR_CONTROL: 0.8,
MAX_HEALTH: 3,
INVULNERABLE_MS: 500,
HURT_BOUNCE_Y: -200,
STOMP_BOUNCE_Y: -250,
BODY_WIDTH: 20,
BODY_HEIGHT: 40,
SPAWN_X: 100,
SPAWN_Y: 400,
};
export const ENEMY = {
SPEED: 80,
POOL_SIZE: 10,
SCORE_VALUE: 100,
STOMP_THRESHOLD: 20,
};
export const UI = {
FONT_SIZE: '20px',
FONT_COLOR: '#ffffff',
HEALTH_COLOR: '#ff4444',
PADDING: 16,
LINE_HEIGHT: 28,
};
export const COLORS = {
DAMAGE_TINT: 0xff0000,
PLATFORM: 0x4a4a4a,
};
export const CAMERA = {
LERP: 0.1,
};src/core/EventBus.ts
import Phaser from 'phaser';
export const EventBus = new Phaser.Events.EventEmitter();
export const Events = {
// Player domain
PLAYER_HEALTH: 'player:health',
PLAYER_DIED: 'player:died',
// Enemy domain
ENEMY_KILLED: 'enemy:killed',
// Score domain
SCORE_CHANGED: 'score:changed',
// Game domain
GAME_OVER: 'game:over',
GAME_RESTART: 'game:restart',
} as const;src/core/GameState.ts
import { PLAYER } from './Constants';
class GameState {
score = 0;
bestScore = 0;
health = PLAYER.MAX_HEALTH;
started = false;
gameOver = false;
reset() {
this.score = 0;
this.health = PLAYER.MAX_HEALTH;
this.started = false;
this.gameOver = false;
// bestScore persists across resets
}
}
export const gameState = new GameState();src/systems/StateMachine.ts
interface StateConfig<T> {
enter?: (owner: T) => void;
update?: (owner: T, delta: number) => void;
exit?: (owner: T) => void;
}
export class StateMachine<T> {
private states = new Map<string, StateConfig<T>>();
private current?: string;
private owner: T;
constructor(owner: T) {
this.owner = owner;
}
addState(name: string, config: StateConfig<T>): this {
this.states.set(name, config);
return this;
}
transition(name: string) {
if (this.current === name) return;
if (this.current) this.states.get(this.current)?.exit?.(this.owner);
this.current = name;
this.states.get(name)?.enter?.(this.owner);
}
update(delta: number) {
if (this.current) this.states.get(this.current)?.update?.(this.owner, delta);
}
get currentState() { return this.current; }
}src/objects/Player.ts
import Phaser from 'phaser';
import { StateMachine } from '../systems/StateMachine';
import { EventBus, Events } from '../core/EventBus';
import { gameState } from '../core/GameState';
import { PLAYER, COLORS } from '../core/Constants';
export class Player extends Phaser.Physics.Arcade.Sprite {
readonly sm: StateMachine<Player>;
cursors!: Phaser.Types.Input.Keyboard.CursorKeys;
private invulnerable = false;
constructor(scene: Phaser.Scene, x: number, y: number) {
super(scene, x, y, 'sprites', 'player-idle-01');
scene.add.existing(this);
scene.physics.add.existing(this);
this.setCollideWorldBounds(true);
this.body!.setSize(PLAYER.BODY_WIDTH, PLAYER.BODY_HEIGHT);
this.cursors = scene.input.keyboard!.createCursorKeys();
this.sm = new StateMachine<Player>(this);
this.sm
.addState('idle', {
enter: (p) => p.play('player-idle'),
update: (p) => {
if (p.cursors.left.isDown || p.cursors.right.isDown) p.sm.transition('walk');
if (p.cursors.up.isDown && p.isGrounded()) p.sm.transition('jump');
},
})
.addState('walk', {
enter: (p) => p.play('player-walk'),
update: (p) => {
if (p.cursors.left.isDown) {
p.setVelocityX(-PLAYER.SPEED);
p.setFlipX(true);
} else if (p.cursors.right.isDown) {
p.setVelocityX(PLAYER.SPEED);
p.setFlipX(false);
} else {
p.sm.transition('idle');
}
if (p.cursors.up.isDown && p.isGrounded()) p.sm.transition('jump');
},
exit: (p) => p.setVelocityX(0),
})
.addState('jump', {
enter: (p) => {
p.setVelocityY(-PLAYER.JUMP_FORCE);
p.play('player-jump');
},
update: (p) => {
if (p.cursors.left.isDown) p.setVelocityX(-PLAYER.SPEED * PLAYER.AIR_CONTROL);
else if (p.cursors.right.isDown) p.setVelocityX(PLAYER.SPEED * PLAYER.AIR_CONTROL);
if (p.isGrounded()) p.sm.transition('idle');
},
})
.addState('hurt', {
enter: (p) => {
p.invulnerable = true;
p.setTint(COLORS.DAMAGE_TINT);
p.setVelocityY(PLAYER.HURT_BOUNCE_Y);
p.scene.time.delayedCall(PLAYER.INVULNERABLE_MS, () => {
p.clearTint();
p.invulnerable = false;
p.sm.transition('idle');
});
},
});
this.sm.transition('idle');
}
isGrounded(): boolean {
return this.body!.blocked.down;
}
takeDamage() {
if (this.invulnerable) return;
gameState.health--;
EventBus.emit(Events.PLAYER_HEALTH, gameState.health);
if (gameState.health <= 0) {
gameState.gameOver = true;
EventBus.emit(Events.PLAYER_DIED);
this.destroy();
} else {
this.sm.transition('hurt');
}
}
update(_time: number, delta: number) {
this.sm.update(delta);
}
}src/objects/EnemyGroup.ts
import Phaser from 'phaser';
import { EventBus, Events } from '../core/EventBus';
import { ENEMY } from '../core/Constants';
class Enemy extends Phaser.Physics.Arcade.Sprite {
private direction = 1;
constructor(scene: Phaser.Scene, x: number, y: number) {
super(scene, x, y, 'sprites', 'enemy-idle');
}
activate(x: number, y: number) {
this.setPosition(x, y);
this.setActive(true);
this.setVisible(true);
this.body!.enable = true;
this.direction = Phaser.Math.Between(0, 1) ? 1 : -1;
this.setVelocityX(ENEMY.SPEED * this.direction);
}
update() {
if (!this.active) return;
if (this.body!.blocked.left) this.direction = 1;
if (this.body!.blocked.right) this.direction = -1;
this.setVelocityX(ENEMY.SPEED * this.direction);
this.setFlipX(this.direction < 0);
}
die() {
this.setActive(false);
this.setVisible(false);
this.body!.enable = false;
EventBus.emit(Events.ENEMY_KILLED, { x: this.x, y: this.y });
}
}
export class EnemyGroup extends Phaser.Physics.Arcade.Group {
constructor(scene: Phaser.Scene) {
super(scene.physics.world, scene, {
classType: Enemy,
maxSize: ENEMY.POOL_SIZE,
runChildUpdate: true,
});
}
spawn(x: number, y: number) {
const enemy = this.getFirstDead(true, x, y) as Enemy | null;
if (enemy) enemy.activate(x, y);
}
}src/scenes/Game.ts
import Phaser from 'phaser';
import { Player } from '../objects/Player';
import { EnemyGroup } from '../objects/EnemyGroup';
import { EventBus, Events } from '../core/EventBus';
import { gameState } from '../core/GameState';
import { GAME, PLAYER, ENEMY, COLORS, CAMERA } from '../core/Constants';
export class Game extends Phaser.Scene {
private player!: Player;
private enemies!: EnemyGroup;
private platforms!: Phaser.Physics.Arcade.StaticGroup;
constructor() { super('Game'); }
create() {
gameState.reset();
gameState.started = true;
// Launch HUD as parallel scene
this.scene.launch('HUD');
// Create level
this.platforms = this.physics.add.staticGroup();
this.createLevel();
// Player
this.player = new Player(this, PLAYER.SPAWN_X, PLAYER.SPAWN_Y);
// Enemies (pooled)
this.enemies = new EnemyGroup(this);
this.spawnEnemies();
// Collisions
this.physics.add.collider(this.player, this.platforms);
this.physics.add.collider(this.enemies, this.platforms);
this.physics.add.overlap(this.player, this.enemies, this.onPlayerEnemyContact, undefined, this);
// Camera
this.cameras.main.startFollow(this.player, true, CAMERA.LERP, CAMERA.LERP);
this.cameras.main.setBounds(0, 0, GAME.WORLD_WIDTH, GAME.HEIGHT);
this.physics.world.setBounds(0, 0, GAME.WORLD_WIDTH, GAME.HEIGHT);
// Events
EventBus.on(Events.PLAYER_DIED, this.onPlayerDied, this);
this.events.on('shutdown', this.cleanup, this);
}
private createLevel() {
// Data-driven: in a real game, load from Tiled JSON
const levelData = [
{ x: 400, y: 584, w: 800 },
{ x: 1200, y: 584, w: 800 },
{ x: 600, y: 450, w: 200 },
{ x: 300, y: 320, w: 150 },
{ x: 900, y: 380, w: 250 },
];
levelData.forEach(p => {
const platform = this.add.rectangle(p.x, p.y, p.w, 32, COLORS.PLATFORM);
this.platforms.add(platform);
});
}
private spawnEnemies() {
const spawnPoints = [
{ x: 500, y: 400 },
{ x: 800, y: 540 },
{ x: 1100, y: 540 },
];
spawnPoints.forEach(sp => this.enemies.spawn(sp.x, sp.y));
}
private onPlayerEnemyContact(
_player: Phaser.Types.Physics.Arcade.GameObjectWithBody,
enemy: Phaser.Types.Physics.Arcade.GameObjectWithBody
) {
const e = enemy as any;
// Stomp from above
if (this.player.body!.velocity.y > 0 && this.player.y < e.y - ENEMY.STOMP_THRESHOLD) {
e.die();
this.player.setVelocityY(PLAYER.STOMP_BOUNCE_Y);
gameState.score += ENEMY.SCORE_VALUE;
EventBus.emit(Events.SCORE_CHANGED, { score: gameState.score });
} else {
this.player.takeDamage();
}
}
private onPlayerDied() {
gameState.bestScore = Math.max(gameState.bestScore, gameState.score);
this.scene.stop('HUD');
this.scene.start('GameOver');
}
update(time: number, delta: number) {
this.player.update(time, delta);
}
private cleanup() {
EventBus.off(Events.PLAYER_DIED, this.onPlayerDied, this);
}
}src/scenes/HUD.ts
import Phaser from 'phaser';
import { EventBus, Events } from '../core/EventBus';
import { gameState } from '../core/GameState';
import { UI } from '../core/Constants';
export class HUD extends Phaser.Scene {
private scoreText!: Phaser.GameObjects.Text;
private healthText!: Phaser.GameObjects.Text;
constructor() { super('HUD'); }
create() {
this.scoreText = this.add.text(UI.PADDING, UI.PADDING, 'Score: 0', {
fontSize: UI.FONT_SIZE, color: UI.FONT_COLOR,
});
this.healthText = this.add.text(UI.PADDING, UI.PADDING + UI.LINE_HEIGHT, `Health: ${gameState.health}`, {
fontSize: UI.FONT_SIZE, color: UI.HEALTH_COLOR,
});
EventBus.on(Events.SCORE_CHANGED, this.onScoreChange, this);
EventBus.on(Events.PLAYER_HEALTH, this.onHealthChange, this);
this.events.on('shutdown', this.cleanup, this);
}
private onScoreChange(data: { score: number }) {
this.scoreText.setText(`Score: ${data.score}`);
}
private onHealthChange(health: number) {
this.healthText.setText(`Health: ${health}`);
}
private cleanup() {
EventBus.off(Events.SCORE_CHANGED, this.onScoreChange, this);
EventBus.off(Events.PLAYER_HEALTH, this.onHealthChange, this);
}
}src/scenes/GameOver.ts
import Phaser from 'phaser';
import { EventBus, Events } from '../core/EventBus';
import { gameState } from '../core/GameState';
import { UI } from '../core/Constants';
export class GameOver extends Phaser.Scene {
constructor() { super('GameOver'); }
create() {
const cx = this.cameras.main.centerX;
const cy = this.cameras.main.centerY;
this.add.text(cx, cy - 50, 'GAME OVER', {
fontSize: '48px', color: '#ff0000',
}).setOrigin(0.5);
this.add.text(cx, cy + 20, `Score: ${gameState.score}`, {
fontSize: UI.FONT_SIZE, color: UI.FONT_COLOR,
}).setOrigin(0.5);
if (gameState.bestScore > 0) {
this.add.text(cx, cy + 60, `Best: ${gameState.bestScore}`, {
fontSize: UI.FONT_SIZE, color: '#ffff00',
}).setOrigin(0.5);
}
this.add.text(cx, cy + 110, 'Click to restart', {
fontSize: '18px', color: '#aaaaaa',
}).setOrigin(0.5);
this.input.once('pointerdown', () => {
EventBus.emit(Events.GAME_RESTART);
this.scene.start('Game');
});
}
}Key Patterns Demonstrated
1. Constants — Every tunable value in Constants.ts, zero hardcoded numbers in logic 2. GameState — Centralized state with reset() for clean restarts, bestScore persistence 3. EventBus — domain:action naming, typed event constants, all communication decoupled 4. State Machine — Player movement uses StateMachine<Player> for clean state transitions 5. Object Pooling — EnemyGroup pools enemies with maxSize and getFirstDead() 6. Parallel Scenes — HUD runs alongside Game as a UI overlay 7. Cleanup — All scenes remove EventBus listeners in shutdown() 8. Data-Driven — Level layout defined as data (would be Tiled JSON in production)
Simple Game Example — Star Collector
A minimal complete Phaser game: collect falling stars, avoid bombs.
src/main.ts
import Phaser from 'phaser';
import { Preloader } from './scenes/Preloader';
import { Game } from './scenes/Game';
import { GameOver } from './scenes/GameOver';
new Phaser.Game({
type: Phaser.AUTO,
width: 800,
height: 600,
parent: 'game-container',
backgroundColor: '#1a1a2e',
scale: {
mode: Phaser.Scale.FIT,
autoCenter: Phaser.Scale.CENTER_BOTH,
},
physics: {
default: 'arcade',
arcade: { gravity: { x: 0, y: 300 } },
},
scene: [Preloader, Game, GameOver],
});src/scenes/Preloader.ts
import Phaser from 'phaser';
export class Preloader extends Phaser.Scene {
constructor() { super('Preloader'); }
preload() {
// In a real game, load an atlas. Here we create simple shapes.
this.load.on('complete', () => this.createTextures());
}
private createTextures() {
// Generate textures procedurally for this example
const g = this.add.graphics();
g.fillStyle(0x00ff00);
g.fillRect(0, 0, 32, 48);
g.generateTexture('player', 32, 48);
g.clear().fillStyle(0xffff00);
g.fillStar(16, 16, 5, 16, 8);
g.generateTexture('star', 32, 32);
g.clear().fillStyle(0xff0000);
g.fillCircle(16, 16, 16);
g.generateTexture('bomb', 32, 32);
g.clear().fillStyle(0x4a4a4a);
g.fillRect(0, 0, 800, 32);
g.generateTexture('ground', 800, 32);
g.destroy();
}
create() {
this.scene.start('Game');
}
}src/scenes/Game.ts
import Phaser from 'phaser';
export class Game extends Phaser.Scene {
private player!: Phaser.Physics.Arcade.Sprite;
private cursors!: Phaser.Types.Input.Keyboard.CursorKeys;
private stars!: Phaser.Physics.Arcade.Group;
private bombs!: Phaser.Physics.Arcade.Group;
private scoreText!: Phaser.GameObjects.Text;
private score = 0;
constructor() { super('Game'); }
create() {
this.score = 0;
// Ground
const ground = this.physics.add.staticImage(400, 584, 'ground');
// Player
this.player = this.physics.add.sprite(400, 450, 'player');
this.player.setCollideWorldBounds(true);
this.physics.add.collider(this.player, ground);
// Stars (pooled group)
this.stars = this.physics.add.group({
key: 'star',
repeat: 11,
setXY: { x: 12, y: 0, stepX: 65 },
});
this.stars.children.iterate((child) => {
const star = child as Phaser.Physics.Arcade.Image;
star.setBounceY(Phaser.Math.FloatBetween(0.2, 0.5));
return true;
});
this.physics.add.collider(this.stars, ground);
this.physics.add.overlap(this.player, this.stars, this.collectStar, undefined, this);
// Bombs
this.bombs = this.physics.add.group();
this.physics.add.collider(this.bombs, ground);
this.physics.add.collider(this.player, this.bombs, this.hitBomb, undefined, this);
// Input
this.cursors = this.input.keyboard!.createCursorKeys();
// UI
this.scoreText = this.add.text(16, 16, 'Score: 0', {
fontSize: '20px',
color: '#ffffff',
});
}
update() {
if (this.cursors.left.isDown) {
this.player.setVelocityX(-200);
} else if (this.cursors.right.isDown) {
this.player.setVelocityX(200);
} else {
this.player.setVelocityX(0);
}
if (this.cursors.up.isDown && this.player.body!.blocked.down) {
this.player.setVelocityY(-400);
}
}
private collectStar(
_player: Phaser.Types.Physics.Arcade.GameObjectWithBody,
star: Phaser.Types.Physics.Arcade.GameObjectWithBody
) {
const s = star as Phaser.Physics.Arcade.Image;
s.disableBody(true, true);
this.score += 10;
this.scoreText.setText(`Score: ${this.score}`);
// All stars collected — spawn new wave + bomb
if (this.stars.countActive(true) === 0) {
this.stars.children.iterate((child) => {
const c = child as Phaser.Physics.Arcade.Image;
c.enableBody(true, c.x, 0, true, true);
return true;
});
const x = Phaser.Math.Between(50, 750);
const bomb = this.bombs.create(x, 16, 'bomb') as Phaser.Physics.Arcade.Image;
bomb.setBounce(1);
bomb.setCollideWorldBounds(true);
bomb.setVelocity(Phaser.Math.Between(-200, 200), 20);
}
}
private hitBomb() {
this.physics.pause();
this.player.setTint(0xff0000);
this.scene.start('GameOver', { score: this.score });
}
}src/scenes/GameOver.ts
import Phaser from 'phaser';
export class GameOver extends Phaser.Scene {
constructor() { super('GameOver'); }
create(data: { score: number }) {
const cx = this.cameras.main.centerX;
const cy = this.cameras.main.centerY;
this.add.text(cx, cy - 50, 'GAME OVER', {
fontSize: '48px',
color: '#ff0000',
}).setOrigin(0.5);
this.add.text(cx, cy + 20, `Score: ${data.score}`, {
fontSize: '24px',
color: '#ffffff',
}).setOrigin(0.5);
this.add.text(cx, cy + 80, 'Click to restart', {
fontSize: '18px',
color: '#aaaaaa',
}).setOrigin(0.5);
this.input.once('pointerdown', () => {
this.scene.start('Game');
});
}
}Game Objects
Custom Game Objects
Extend Phaser's built-in classes to encapsulate behavior:
import Phaser from 'phaser';
export class Player extends Phaser.Physics.Arcade.Sprite {
private speed = 200;
private health = 100;
private cursors: Phaser.Types.Input.Keyboard.CursorKeys;
constructor(scene: Phaser.Scene, x: number, y: number) {
super(scene, x, y, 'sprites', 'player-idle');
// Add to scene and enable physics
scene.add.existing(this);
scene.physics.add.existing(this);
this.setCollideWorldBounds(true);
this.cursors = scene.input.keyboard!.createCursorKeys();
}
update(_time: number, _delta: number) {
if (this.cursors.left.isDown) {
this.setVelocityX(-this.speed);
this.setFlipX(true);
} else if (this.cursors.right.isDown) {
this.setVelocityX(this.speed);
this.setFlipX(false);
} else {
this.setVelocityX(0);
}
if (this.cursors.up.isDown && this.body!.blocked.down) {
this.setVelocityY(-400);
}
}
takeDamage(amount: number) {
this.health -= amount;
this.setTint(0xff0000);
this.scene.time.delayedCall(100, () => this.clearTint());
if (this.health <= 0) {
this.emit('died');
this.destroy();
}
}
}Mobile-Friendly Input Pattern
Instead of having the Player read keyboard input directly (via this.cursors), have the Scene build an inputState object from all sources (keyboard + touch + gamepad) and pass it to player.update(). This keeps Player input-source-agnostic:
// In Scene update():
const inputState = {
left: this.cursors.left.isDown || this.touchLeft,
right: this.cursors.right.isDown || this.touchRight,
jump: Phaser.Input.Keyboard.JustDown(this.spaceKey) || this.touchJump,
};
this.player.update(time, delta, inputState);
// In Player.update():
update(_time: number, _delta: number, input: InputState) {
if (input.left) {
this.setVelocityX(-this.speed);
this.setFlipX(true);
} else if (input.right) {
this.setVelocityX(this.speed);
this.setFlipX(false);
} else {
this.setVelocityX(0);
}
if (input.jump && this.body!.blocked.down) {
this.setVelocityY(-400);
}
}Registering with GameObjectFactory
Register custom objects so they can be created with this.add.player(...):
// At the bottom of Player.ts
Phaser.GameObjects.GameObjectFactory.register('player',
function (this: Phaser.GameObjects.GameObjectFactory, x: number, y: number) {
const player = new Player(this.scene, x, y);
this.displayList.add(player);
this.updateList.add(player);
return player;
}
);
// Usage in scene:
// this.add.player(400, 300);Groups (Object Pooling)
Use Groups to pool frequently created/destroyed objects:
export class BulletGroup extends Phaser.Physics.Arcade.Group {
constructor(scene: Phaser.Scene) {
super(scene.physics.world, scene, {
classType: Bullet,
maxSize: 30,
runChildUpdate: true, // Calls update() on active children
createCallback: (obj) => {
const bullet = obj as Bullet;
bullet.setActive(false);
bullet.setVisible(false);
},
});
}
fire(x: number, y: number, direction: number) {
const bullet = this.getFirstDead(false) as Bullet | null;
if (bullet) {
bullet.fire(x, y, direction);
}
}
}
class Bullet extends Phaser.Physics.Arcade.Sprite {
constructor(scene: Phaser.Scene, x: number, y: number) {
super(scene, x, y, 'sprites', 'bullet');
}
fire(x: number, y: number, direction: number) {
this.setPosition(x, y);
this.setActive(true);
this.setVisible(true);
this.body!.enable = true;
this.setVelocityX(direction * 500);
}
update() {
// Deactivate when off-screen
if (this.x < -50 || this.x > 850) {
this.setActive(false);
this.setVisible(false);
this.body!.enable = false;
}
}
}Containers
Use Containers to group related objects that move together:
export class HealthBar extends Phaser.GameObjects.Container {
private bar: Phaser.GameObjects.Rectangle;
private bg: Phaser.GameObjects.Rectangle;
constructor(scene: Phaser.Scene, x: number, y: number) {
super(scene, x, y);
this.bg = scene.add.rectangle(0, 0, 50, 6, 0x333333);
this.bar = scene.add.rectangle(0, 0, 50, 6, 0x00ff00);
this.add([this.bg, this.bar]);
scene.add.existing(this);
}
setPercent(value: number) {
this.bar.width = 50 * Math.max(0, Math.min(1, value));
}
}Container caveats:
- Children of containers are not individually batched — this breaks WebGL batching
- Avoid nesting containers more than 1 level deep
- For large numbers of similar objects, use Groups instead
- Containers don't have physics bodies; add physics to children individually
Choosing the Right Base Class
| Need | Use |
|---|---|
| Static image | Phaser.GameObjects.Image |
| Animated sprite | Phaser.GameObjects.Sprite |
| Sprite with physics | Phaser.Physics.Arcade.Sprite |
| Group of related visuals | Phaser.GameObjects.Container |
| Many similar objects (pooling) | Phaser.Physics.Arcade.Group |
| Tilemap layer | Phaser.Tilemaps.TilemapLayer |
| Text | Phaser.GameObjects.Text (or BitmapText for performance) |
| Shapes | Phaser.GameObjects.Rectangle, Circle, etc. |
Update Pattern
Game objects with custom update() methods need to be called explicitly unless they're in a Group with runChildUpdate: true:
// Option 1: Call manually in scene update
update(time: number, delta: number) {
this.player.update(time, delta);
}
// Option 2: Add to update list
this.sys.updateList.add(this.player);
// Option 3: Use Group with runChildUpdate
const enemies = this.add.group({ runChildUpdate: true });Button Pattern (Container + Graphics + Text)
Buttons require careful z-ordering. Use a Container holding Graphics (background) then Text (label) — in that order. The Container itself is interactive.
ALWAYS use this exact pattern for clickable buttons. Do not use Zone, do not draw Graphics on top of Text, and do not set interactivity on anything other than the Container.
createButton(scene, x, y, label, callback) {
const btnW = Math.max(GAME.WIDTH * UI.BTN_W_RATIO, 160);
const btnH = Math.max(GAME.HEIGHT * UI.BTN_H_RATIO, UI.MIN_TOUCH);
const radius = UI.BTN_RADIUS;
const container = scene.add.container(x, y);
// 1. Graphics background (added FIRST — renders behind text)
const bg = scene.add.graphics();
bg.fillStyle(COLORS.BTN_PRIMARY, 1);
bg.fillRoundedRect(-btnW / 2, -btnH / 2, btnW, btnH, radius);
container.add(bg);
// 2. Text label (added SECOND — renders on top of background)
const fontSize = Math.round(GAME.HEIGHT * UI.BODY_RATIO);
const text = scene.add.text(0, 0, label, {
fontSize: fontSize + 'px',
fontFamily: UI.FONT,
color: COLORS.BTN_TEXT,
fontStyle: 'bold',
}).setOrigin(0.5);
container.add(text);
// 3. Make the CONTAINER interactive (not the graphics or text)
container.setSize(btnW, btnH);
container.setInteractive({ useHandCursor: true });
const fillBtn = (gfx, color) => {
gfx.clear();
gfx.fillStyle(color, 1);
gfx.fillRoundedRect(-btnW / 2, -btnH / 2, btnW, btnH, radius);
};
container.on('pointerover', () => {
fillBtn(bg, COLORS.BTN_PRIMARY_HOVER);
scene.tweens.add({ targets: container, scaleX: 1.05, scaleY: 1.05, duration: 80 });
});
container.on('pointerout', () => {
fillBtn(bg, COLORS.BTN_PRIMARY);
scene.tweens.add({ targets: container, scaleX: 1, scaleY: 1, duration: 80 });
});
container.on('pointerdown', () => {
fillBtn(bg, COLORS.BTN_PRIMARY_PRESS);
container.setScale(0.95);
});
container.on('pointerup', () => {
container.setScale(1);
callback();
});
return container;
}Broken patterns (do NOT use):
- Drawing Graphics on top of Text (hides the label)
- Using a Zone for interactivity with Graphics drawn over it (Zone becomes unreachable)
- Setting
setAlpha(0)on an interactive object and layering visuals over it
No-Asset Visual Design
Techniques for making asset-free Phaser games look polished using only procedural graphics (Phaser.GameObjects.Graphics), shapes, particles, and tweens. No sprite sheets, no image files — just code.
Color Palette
Pick a cohesive 3-5 color palette before writing any visual code. Define it in Constants.ts:
// Use coolors.co or lospec.com/palette-list for inspiration
export const PALETTE = {
SKY_TOP: 0x1a1a2e,
SKY_BOTTOM: 0x16213e,
ACCENT: 0xe94560,
FOREGROUND: 0x0f3460,
HIGHLIGHT: 0xf5d742,
TEXT: '#ffffff',
} as const;Rules:
- Every color in the game comes from the palette — no ad-hoc hex values in game logic
- Limit to 5 colors max. Constraint reads as intentional style, not placeholder art
- Use opacity variations (0.3, 0.5, 0.8) of palette colors for depth rather than adding new colors
Gradient Backgrounds
Flat solid backgrounds look unfinished. Always use gradients:
// Sky gradient — call once in create(), behind everything
private createSkyGradient(): void {
const g = this.add.graphics();
g.fillGradientStyle(
PALETTE.SKY_TOP, PALETTE.SKY_TOP,
PALETTE.SKY_BOTTOM, PALETTE.SKY_BOTTOM,
1
);
g.fillRect(0, 0, GAME.WIDTH, GAME.HEIGHT);
g.setDepth(-100);
}Time-of-Day Color Shifts
Lerp between palettes for dawn/dusk cycles:
private lerpColor(a: number, b: number, t: number): number {
const ar = (a >> 16) & 0xff, ag = (a >> 8) & 0xff, ab = a & 0xff;
const br = (b >> 16) & 0xff, bg = (b >> 8) & 0xff, bb = b & 0xff;
const r = Math.round(ar + (br - ar) * t);
const g = Math.round(ag + (bg - ag) * t);
const blue = Math.round(ab + (bb - ab) * t);
return (r << 16) | (g << 8) | blue;
}Parallax Depth
3-4 layers minimum. Each layer moves at a different speed relative to the camera or player. Even subtle differences (0.1x, 0.3x, 0.6x, 1x) create massive depth perception.
interface ParallaxLayer {
elements: Phaser.GameObjects.GameObject[];
speed: number;
}
private layers: ParallaxLayer[] = [];
private createParallax(): void {
// Far background — barely moves
this.layers.push({
elements: this.createCloudLayer(3, 0.15),
speed: 0.1,
});
// Mid layer
this.layers.push({
elements: this.createHillLayer(0.4),
speed: 0.3,
});
// Near layer — moves faster
this.layers.push({
elements: this.createCloudLayer(5, 0.5),
speed: 0.6,
});
}
update(_time: number, delta: number): void {
for (const layer of this.layers) {
for (const el of layer.elements) {
(el as Phaser.GameObjects.Shape).x -= layer.speed * (delta / 16);
// Wrap around
if ((el as Phaser.GameObjects.Shape).x < -100) {
(el as Phaser.GameObjects.Shape).x = GAME.WIDTH + Phaser.Math.Between(50, 200);
}
}
}
}Procedural Elements
Clouds
Rounded rectangles or overlapping circles with slight transparency, random sizes, drifting slowly:
private createCloud(x: number, y: number, scale: number, alpha: number): Phaser.GameObjects.Graphics {
const g = this.add.graphics();
g.fillStyle(0xffffff, alpha);
// Overlapping circles for puffy cloud shape
const baseR = 20 * scale;
g.fillCircle(0, 0, baseR);
g.fillCircle(-baseR * 0.7, baseR * 0.2, baseR * 0.7);
g.fillCircle(baseR * 0.7, baseR * 0.2, baseR * 0.8);
g.fillCircle(baseR * 0.3, -baseR * 0.3, baseR * 0.6);
g.setPosition(x, y);
return g;
}
private createCloudLayer(count: number, alphaBase: number): Phaser.GameObjects.Graphics[] {
const clouds: Phaser.GameObjects.Graphics[] = [];
for (let i = 0; i < count; i++) {
const x = Phaser.Math.Between(0, GAME.WIDTH);
const y = Phaser.Math.Between(30, GAME.HEIGHT * 0.4);
const scale = Phaser.Math.FloatBetween(0.5, 1.5);
const alpha = alphaBase * Phaser.Math.FloatBetween(0.5, 1.0);
clouds.push(this.createCloud(x, y, scale, alpha));
}
return clouds;
}Mountains / Hills
Sine waves or noise drawn to Graphics, layered with different opacities:
private createHills(color: number, alpha: number, amplitude: number, frequency: number, yOffset: number, depth: number): Phaser.GameObjects.Graphics {
const g = this.add.graphics();
g.fillStyle(color, alpha);
g.beginPath();
g.moveTo(0, GAME.HEIGHT);
for (let x = 0; x <= GAME.WIDTH; x += 4) {
const y = yOffset + Math.sin(x * frequency * 0.01) * amplitude
+ Math.sin(x * frequency * 0.023) * (amplitude * 0.5);
g.lineTo(x, y);
}
g.lineTo(GAME.WIDTH, GAME.HEIGHT);
g.closePath();
g.fillPath();
g.setDepth(depth);
return g;
}Ambient Particles
Use Phaser's particle system for dust, leaves, light motes — ambient life without assets:
private createAmbientParticles(): void {
// Create a tiny circle texture for particles
const g = this.add.graphics();
g.fillStyle(0xffffff);
g.fillCircle(4, 4, 4);
g.generateTexture('particle', 8, 8);
g.destroy();
this.add.particles(0, 0, 'particle', {
x: { min: 0, max: GAME.WIDTH },
y: { min: 0, max: GAME.HEIGHT },
scale: { start: 0.3, end: 0 },
alpha: { start: 0.3, end: 0 },
speed: { min: 5, max: 20 },
lifespan: 4000,
frequency: 500,
blendMode: 'ADD',
tint: PALETTE.HIGHLIGHT,
});
}"Lighting" Without Shaders
Vignette Overlay
Dark edges, transparent center — adds instant cinematic polish:
private createVignette(): void {
const g = this.add.graphics();
const cx = GAME.WIDTH / 2;
const cy = GAME.HEIGHT / 2;
const r = Math.max(GAME.WIDTH, GAME.HEIGHT) * 0.7;
// Radial gradient approximation with concentric rings
const steps = 20;
for (let i = steps; i >= 0; i--) {
const t = i / steps;
const alpha = (1 - t) * 0.6; // Max 0.6 opacity at edges
g.fillStyle(0x000000, alpha);
g.fillCircle(cx, cy, r * t + r * 0.3);
}
g.setDepth(1000); // Above everything
}Player Glow
Subtle radial gradient following the player:
private createGlow(target: Phaser.GameObjects.GameObject, color: number, radius: number): Phaser.GameObjects.Graphics {
const g = this.add.graphics();
const steps = 10;
for (let i = steps; i >= 0; i--) {
const t = i / steps;
g.fillStyle(color, t * 0.15);
g.fillCircle(0, 0, radius * (1 - t * 0.5));
}
g.setBlendMode(Phaser.BlendModes.ADD);
return g;
}
// In update: glow.setPosition(player.x, player.y);Sun Rays
Additive blend mode on white/yellow shapes:
private createSunRays(): void {
const g = this.add.graphics();
g.setBlendMode(Phaser.BlendModes.ADD);
for (let i = 0; i < 5; i++) {
const angle = Phaser.Math.DegToRad(-30 + i * 15);
const length = GAME.HEIGHT * 1.5;
g.fillStyle(0xffffff, 0.03);
g.beginPath();
g.moveTo(GAME.WIDTH * 0.8, 0);
g.lineTo(
GAME.WIDTH * 0.8 + Math.cos(angle) * length,
Math.sin(angle) * length,
);
g.lineTo(
GAME.WIDTH * 0.8 + Math.cos(angle + 0.05) * length,
Math.sin(angle + 0.05) * length,
);
g.closePath();
g.fillPath();
}
g.setDepth(50);
}Juice
Squash & Stretch
Apply scale tweens on jumps, bounces, and landings:
// On jump
this.tweens.add({
targets: player,
scaleX: 0.8,
scaleY: 1.3,
duration: 100,
yoyo: true,
ease: 'Quad.easeOut',
});
// Continuous velocity-based stretch (no tween needed)
update(): void {
player.scaleY = 1 + (player.body!.velocity.y * 0.001);
player.scaleX = 1 - (Math.abs(player.body!.velocity.y) * 0.0005);
}Screen Shake
On impacts, deaths, explosions. Use intensities that are visible in video — subtle shakes disappear in compression.
// Light shake (score, small hit)
this.cameras.main.shake(100, 0.008);
// Medium shake (enemy destroyed, combo)
this.cameras.main.shake(150, 0.015);
// Heavy shake (death, streak milestone, big explosion)
this.cameras.main.shake(200, 0.025);Trail Effects
Spawn fading shapes behind moving objects:
private spawnTrail(x: number, y: number, color: number): void {
const trail = this.add.circle(x, y, 6, color, 0.5);
this.tweens.add({
targets: trail,
alpha: 0,
scale: 0.2,
duration: 300,
ease: 'Quad.easeOut',
onComplete: () => trail.destroy(),
});
}
// Call in update for moving entities:
// if (frameCount % 3 === 0) this.spawnTrail(player.x, player.y, PALETTE.ACCENT);Flash Effects
Brief white flash on score, hit, or transition:
private flash(duration = 100, color = 0xffffff): void {
this.cameras.main.flash(duration,
(color >> 16) & 0xff,
(color >> 8) & 0xff,
color & 0xff,
);
}Slow Motion
Dramatic death or impact moments:
private slowMo(durationMs: number, timeScale = 0.3): void {
this.time.timeScale = timeScale;
this.time.delayedCall(durationMs * timeScale, () => {
this.time.timeScale = 1;
});
}Easing Functions
Never use linear tweens. Always specify an easing:
| Effect | Easing |
|---|---|
| Jump / bounce | Bounce.easeOut |
| UI slide in | Back.easeOut |
| Fade out | Quad.easeIn |
| Score pop | Elastic.easeOut |
| Smooth movement | Sine.easeInOut |
| Impact | Expo.easeOut |
// Score pop animation
private popScore(text: Phaser.GameObjects.Text): void {
this.tweens.add({
targets: text,
scale: 1.5,
duration: 150,
yoyo: true,
ease: 'Elastic.easeOut',
});
}Spectacle Patterns
These patterns make games visually compelling in short video clips. Wire them to SPECTACLE_* events from the EventBus so the design pass can plug them in without touching gameplay code.
Opening Entrance Animation
Fires in create() before any player input. The first 3 seconds decide whether a viewer keeps watching.
// Flash + player slam-in
private playEntrance(): void {
this.cameras.main.flash(300, 255, 255, 255, true);
// Player starts above screen, slams into position
const targetY = this.player.y;
this.player.y = -100 * PX;
this.tweens.add({
targets: this.player,
y: targetY,
duration: 400,
ease: 'Bounce.easeOut',
onComplete: () => {
this.cameras.main.shake(150, 0.012);
emitBurst(this, this.player.x, this.player.y, 20, PALETTE.ACCENT);
eventBus.emit(Events.SPECTACLE_ENTRANCE);
},
});
// Optional flavor text — use only when it fits the game's vibe
// (e.g., "GO!" for racing, "DODGE!" for avoidance, "FIGHT!" for combat)
const goText = this.add.text(GAME.WIDTH / 2, GAME.HEIGHT / 2, 'GO!', {
fontSize: `${64 * PX}px`, fontFamily: 'Arial Black',
color: '#ffffff', stroke: '#000000', strokeThickness: 6 * PX,
}).setOrigin(0.5).setScale(0).setDepth(500);
this.tweens.add({
targets: goText,
scale: 1.8,
alpha: 0,
duration: 600,
ease: 'Back.easeOut',
onComplete: () => goText.destroy(),
});
}Combo Counter with Scaling Text
Grows with consecutive hits. Wire to SPECTACLE_COMBO.
private showCombo(combo: number): void {
const size = Math.min(32 + combo * 4, 72);
const comboText = this.add.text(GAME.WIDTH / 2, GAME.HEIGHT * 0.3, `${combo}x COMBO`, {
fontSize: `${size * PX}px`, fontFamily: 'Arial Black',
color: '#ffff00', stroke: '#000000', strokeThickness: 4 * PX,
}).setOrigin(0.5).setScale(1.8).setDepth(400);
this.tweens.add({
targets: comboText,
scale: 1,
y: comboText.y - 30 * PX,
alpha: 0,
duration: 700,
ease: 'Elastic.easeOut',
onComplete: () => comboText.destroy(),
});
}Hit Freeze Frame (Hit Stop)
60ms physics pause on impact. Makes hits feel powerful.
private hitFreeze(): void {
this.physics.world.pause();
this.time.delayedCall(60, () => {
this.physics.world.resume();
});
}Screen-Wide Flash Burst
Colored flashes for different event types.
private flashBurst(color: number, alpha = 0.4): void {
const overlay = this.add.rectangle(
GAME.WIDTH / 2, GAME.HEIGHT / 2,
GAME.WIDTH, GAME.HEIGHT, color, alpha,
).setDepth(900).setBlendMode(Phaser.BlendModes.ADD);
this.tweens.add({
targets: overlay,
alpha: 0,
duration: 150,
onComplete: () => overlay.destroy(),
});
}Color Cycling Background
Hue shifts over time for ambient visual energy.
private bgHue = 0;
private bgGraphics: Phaser.GameObjects.Graphics;
private updateBackgroundHue(delta: number): void {
this.bgHue = (this.bgHue + delta * 0.02) % 360;
const color = Phaser.Display.Color.HSLToColor(this.bgHue / 360, 0.6, 0.15);
this.bgGraphics.clear();
this.bgGraphics.fillStyle(color.color, 1);
this.bgGraphics.fillRect(0, 0, GAME.WIDTH, GAME.HEIGHT);
}Pulsing Background on Score
Additive blend overlay that flashes on score events.
private createScorePulse(): void {
this.scorePulse = this.add.rectangle(
GAME.WIDTH / 2, GAME.HEIGHT / 2,
GAME.WIDTH, GAME.HEIGHT, PALETTE.ACCENT, 0,
).setDepth(-50).setBlendMode(Phaser.BlendModes.ADD);
eventBus.on(Events.SCORE_CHANGED, () => {
this.scorePulse.setAlpha(0.15);
this.tweens.add({
targets: this.scorePulse,
alpha: 0,
duration: 300,
ease: 'Quad.easeOut',
});
});
}Entity Entrance Animations
Pop-in and slam-in patterns for spawning entities.
// Pop-in: entity appears from scale 0
private popIn(target: Phaser.GameObjects.GameObject, delay = 0): void {
(target as any).setScale(0);
this.tweens.add({
targets: target,
scale: 1,
duration: 300,
delay,
ease: 'Back.easeOut',
});
}
// Slam-in: entity drops from above with bounce
private slamIn(target: Phaser.GameObjects.GameObject, targetY: number, delay = 0): void {
(target as any).y = -50 * PX;
this.tweens.add({
targets: target,
y: targetY,
duration: 350,
delay,
ease: 'Bounce.easeOut',
onComplete: () => {
this.cameras.main.shake(80, 0.006);
},
});
}Persistent Player Trail
Continuous particle spawn behind the player.
private createPlayerTrail(): void {
this.playerTrail = this.add.particles(0, 0, 'particle', {
follow: this.player,
scale: { start: 0.6, end: 0 },
alpha: { start: 0.5, end: 0 },
speed: { min: 5, max: 15 },
lifespan: 400,
frequency: 30,
blendMode: 'ADD',
tint: PALETTE.ACCENT,
});
}Particle Ring Burst
Expanding ring for milestones. Higher visual impact than a random burst.
private ringBurst(x: number, y: number, color: number, count = 24): void {
for (let i = 0; i < count; i++) {
const angle = (Math.PI * 2 * i) / count;
const dist = 80 * PX + Math.random() * 20 * PX;
const particle = this.add.circle(x, y, 4 * PX, color, 1);
this.tweens.add({
targets: particle,
x: x + Math.cos(angle) * dist,
y: y + Math.sin(angle) * dist,
alpha: 0,
scale: 0.3,
duration: 500,
ease: 'Quad.easeOut',
onComplete: () => particle.destroy(),
});
}
}Large Spectacle Burst
Higher count, multi-color variant for big moments (streaks, game over).
private spectacleBurst(x: number, y: number, colors: number[], count = 30): void {
for (let i = 0; i < count; i++) {
const angle = Math.random() * Math.PI * 2;
const speed = 80 + Math.random() * 120;
const color = colors[i % colors.length];
const size = (3 + Math.random() * 4) * PX;
const particle = this.add.circle(x, y, size, color, 1);
this.tweens.add({
targets: particle,
x: x + Math.cos(angle) * speed * PX,
y: y + Math.sin(angle) * speed * PX,
alpha: 0,
scale: 0.1,
duration: 500 + Math.random() * 300,
ease: 'Quad.easeOut',
onComplete: () => particle.destroy(),
});
}
}Streak Milestone Announcements
Full-screen text slam for streak milestones (5x, 10x, 25x).
private announceStreak(streak: number): void {
const labels: Record<number, string> = { 5: 'ON FIRE!', 10: 'UNSTOPPABLE!', 25: 'LEGENDARY!' };
const label = labels[streak] || `${streak}x STREAK`;
const text = this.add.text(GAME.WIDTH / 2, GAME.HEIGHT / 2, label, {
fontSize: `${80 * PX}px`, fontFamily: 'Arial Black',
color: '#ffffff', stroke: '#000000', strokeThickness: 8 * PX,
}).setOrigin(0.5).setScale(3).setAlpha(0).setDepth(500);
this.tweens.add({
targets: text,
scale: 1,
alpha: 1,
duration: 300,
ease: 'Back.easeOut',
hold: 400,
yoyo: true,
onComplete: () => text.destroy(),
});
this.cameras.main.shake(200, 0.02);
this.spectacleBurst(GAME.WIDTH / 2, GAME.HEIGHT / 2,
[PALETTE.ACCENT, PALETTE.HIGHLIGHT, 0xffffff], 40);
}Drawing Game Entities with Graphics
Simple Sprite-Like Entity
private drawBird(g: Phaser.GameObjects.Graphics): void {
// Body
g.fillStyle(PALETTE.ACCENT);
g.fillRoundedRect(-15, -12, 30, 24, 8);
// Eye (white circle + black pupil)
g.fillStyle(0xffffff);
g.fillCircle(8, -4, 6);
g.fillStyle(0x000000);
g.fillCircle(10, -4, 3);
// Beak
g.fillStyle(PALETTE.HIGHLIGHT);
g.fillTriangle(15, -2, 15, 6, 24, 2);
// Wing
g.fillStyle(PALETTE.FOREGROUND);
g.fillEllipse(-4, 4, 16, 10);
}Animated Wing / Bobbing
private wingAngle = 0;
update(delta: number): void {
this.wingAngle += delta * 0.01;
const wingY = Math.sin(this.wingAngle) * 3;
// Redraw wing at offset wingY, or tween wing child object
}Checklist
When building an asset-free game, verify:
- [ ] Color palette defined in Constants (3-5 colors max)
- [ ] Gradient background (never flat solid)
- [ ] At least 2 parallax layers
- [ ] Ambient particles or drifting elements
- [ ] Squash/stretch on player movement
- [ ] Screen shake on impacts
- [ ] Eased tweens on all animations (never linear)
- [ ] Score/text pop on change
- [ ] Scene transitions (fade, flash, or slide)
- [ ] Consistent shape language (all rounded, or all angular — pick one)
Viral Clip Checklist
Every game is captured as a 13-second silent video clip for social media. Design for a viewer scrolling with sound off.
First 3 seconds (before player input)
- [ ] Screen flash on scene start (white or accent color, 200-300ms)
- [ ] Player entrance animation — slam-in or pop-in, not a static spawn
- [ ] Landing particles — burst of 15-20 particles at spawn position
- [ ] Ambient motion — background particles, color cycling, or parallax drift active immediately
- [ ] Optional flavor text — "GO!", "DODGE!", etc. only when it naturally fits the game's theme
Every action (seconds 3-13)
- [ ] Particle burst on every player action (minimum 12 particles per burst)
- [ ] Floating text on every score event (28px+ font, scale 1.8 start with Elastic.easeOut)
- [ ] Screen shake on every hit/score (minimum intensity 0.008)
- [ ] Background pulse on score change (additive blend flash, alpha 0.15)
- [ ] Player trail — continuous particle spawn behind the player
- [ ] Combo text visible at 2x combo and above (scaling with combo count)
- [ ] Streak announcement at milestones (5x, 10x, 25x — full-screen text slam)
- [ ] Hit freeze on destruction events (60ms physics pause)
Intensity targets
- Particle bursts: 12-30 count per event (never fewer than 10)
- Screen shake range: 0.008 (light) to 0.025 (heavy)
- Floating text: 28px minimum, starting scale 1.8
- Flash overlays: alpha 0.3-0.5 for visibility in compressed video
- At least one visual effect firing every 0.5 seconds during active gameplay
Advanced Patterns
ECS with bitECS
bitECS is a high-performance Entity Component System. Phaser 4 uses it internally.
npm install bitecsimport { defineComponent, defineQuery, defineSystem, addEntity, addComponent, Types, createWorld } from 'bitecs';
// Components are pure data
const Position = defineComponent({ x: Types.f32, y: Types.f32 });
const Velocity = defineComponent({ x: Types.f32, y: Types.f32 });
const Health = defineComponent({ current: Types.ui16, max: Types.ui16 });
// Queries select entities with specific components
const movementQuery = defineQuery([Position, Velocity]);
// Systems operate on queried entities
const movementSystem = defineSystem((world) => {
const entities = movementQuery(world);
for (const eid of entities) {
Position.x[eid] += Velocity.x[eid];
Position.y[eid] += Velocity.y[eid];
}
return world;
});
// In your scene:
const world = createWorld();
const player = addEntity(world);
addComponent(world, Position, player);
addComponent(world, Velocity, player);
Position.x[player] = 400;
Position.y[player] = 300;
// In update:
movementSystem(world);Bridging bitECS with Phaser
Map ECS entities to Phaser sprites:
const spriteMap = new Map<number, Phaser.GameObjects.Sprite>();
function createEnemy(world: any, scene: Phaser.Scene, x: number, y: number) {
const eid = addEntity(world);
addComponent(world, Position, eid);
addComponent(world, Velocity, eid);
addComponent(world, Health, eid);
Position.x[eid] = x;
Position.y[eid] = y;
Health.current[eid] = 100;
Health.max[eid] = 100;
const sprite = scene.add.sprite(x, y, 'sprites', 'enemy');
spriteMap.set(eid, sprite);
return eid;
}
// Render system syncs ECS data to Phaser sprites
const renderSystem = defineSystem((world) => {
const entities = movementQuery(world);
for (const eid of entities) {
const sprite = spriteMap.get(eid);
if (sprite) {
sprite.setPosition(Position.x[eid], Position.y[eid]);
}
}
return world;
});State Machine (Generic)
A reusable state machine for any entity:
export class StateMachine<T> {
private states = new Map<string, {
enter?: (owner: T) => void;
update?: (owner: T, delta: number) => void;
exit?: (owner: T) => void;
}>();
private current?: string;
private owner: T;
constructor(owner: T) {
this.owner = owner;
}
addState(name: string, config: {
enter?: (owner: T) => void;
update?: (owner: T, delta: number) => void;
exit?: (owner: T) => void;
}) {
this.states.set(name, config);
return this;
}
transition(name: string) {
if (this.current === name) return;
if (this.current) {
this.states.get(this.current)?.exit?.(this.owner);
}
this.current = name;
this.states.get(name)?.enter?.(this.owner);
}
update(delta: number) {
if (this.current) {
this.states.get(this.current)?.update?.(this.owner, delta);
}
}
get currentState() { return this.current; }
}Usage:
const sm = new StateMachine(this.player);
sm.addState('idle', {
enter: (p) => p.play('idle'),
update: (p) => { if (p.cursors.left.isDown) sm.transition('walk'); },
})
.addState('walk', {
enter: (p) => p.play('walk'),
update: (p, delta) => { /* movement logic */ },
exit: (p) => p.setVelocityX(0),
});
sm.transition('idle');Singleton Game Manager
For data that persists across scenes (settings, save data, analytics):
export class GameManager {
private static instance: GameManager;
private game!: Phaser.Game;
private constructor() {}
static getInstance(): GameManager {
if (!GameManager.instance) {
GameManager.instance = new GameManager();
}
return GameManager.instance;
}
init(game: Phaser.Game) {
this.game = game;
}
get registry() { return this.game.registry; }
saveProgress(data: Record<string, unknown>) {
localStorage.setItem('save', JSON.stringify(data));
}
loadProgress(): Record<string, unknown> | null {
const raw = localStorage.getItem('save');
return raw ? JSON.parse(raw) : null;
}
}Alternatively, use this.game.registry directly for simple cross-scene data — it's built in and doesn't need a custom class.
Event Bus
Decouple systems with a shared event emitter:
// src/systems/EventBus.ts
import Phaser from 'phaser';
export const EventBus = new Phaser.Events.EventEmitter();
// Producer (in any scene or object):
EventBus.emit('enemy-killed', { type: 'goblin', x: 100, y: 200 });
// Consumer (in another scene or system):
EventBus.on('enemy-killed', (data: { type: string; x: number; y: number }) => {
spawnLoot(data.x, data.y);
updateScore(data.type);
});
// Clean up in shutdown:
EventBus.off('enemy-killed', this.handler, this);Data-Driven Level Design
Use Tiled map editor for levels:
// Load in Preloader
this.load.tilemapTiledJSON('level1', 'assets/tilemaps/level1.json');
this.load.image('tileset', 'assets/tilemaps/tileset.png');
// Create in Game scene
const map = this.make.tilemap({ key: 'level1' });
const tileset = map.addTilesetImage('tileset', 'tileset')!;
const ground = map.createLayer('Ground', tileset)!;
ground.setCollisionByProperty({ collides: true });
this.physics.add.collider(this.player, ground);
// Spawn objects from Tiled object layer
const spawnPoints = map.getObjectLayer('Spawns')!;
spawnPoints.objects.forEach(obj => {
if (obj.type === 'enemy') {
this.spawnEnemy(obj.x!, obj.y!);
}
});Scene Plugin Pattern
For functionality shared across many scenes, create a Scene Plugin:
export class AudioPlugin extends Phaser.Plugins.ScenePlugin {
private music?: Phaser.Sound.BaseSound;
boot() {
this.systems!.events.on('shutdown', this.shutdown, this);
}
playMusic(key: string) {
if (this.music) this.music.stop();
this.music = this.scene!.sound.add(key, { loop: true });
this.music.play();
}
shutdown() {
this.music?.stop();
}
}
// Register in game config:
plugins: {
scene: [{ key: 'audio', plugin: AudioPlugin, mapping: 'audio' }],
}
// Use in any scene:
this.audio.playMusic('bgm');Physics & Movement
Choosing a Physics Engine
| Feature | Arcade | Matter.js |
|---|---|---|
| Speed | Fast | Slower |
| Body shapes | AABB rectangles, circles | Any polygon, compound shapes |
| Rotation physics | No | Yes |
| Constraints/joints | No | Yes |
| Best for | Platformers, top-down, shooters | Puzzle physics, ragdolls, realistic sims |
Never mix physics engines in the same game.
Arcade Physics Setup
// In game config
physics: {
default: 'arcade',
arcade: {
gravity: { x: 0, y: 300 },
debug: false, // Set true during development
},
}Collisions
// In scene create():
// Collide two objects/groups (both react)
this.physics.add.collider(this.player, this.platforms);
this.physics.add.collider(this.enemies, this.platforms);
// Overlap (trigger callback, no physical reaction)
this.physics.add.overlap(
this.player,
this.coins,
this.collectCoin,
undefined,
this
);
private collectCoin(
player: Phaser.Types.Physics.Arcade.GameObjectWithBody,
coin: Phaser.Types.Physics.Arcade.GameObjectWithBody
) {
const c = coin as Coin;
c.setActive(false);
c.setVisible(false);
c.body!.enable = false;
this.registry.inc('score', 10);
}Collision Groups (Matter.js)
const categoryPlayer = this.matter.world.nextCategory();
const categoryEnemy = this.matter.world.nextCategory();
const categoryPlatform = this.matter.world.nextCategory();
player.setCollisionCategory(categoryPlayer);
player.setCollidesWith([categoryEnemy, categoryPlatform]);
enemy.setCollisionCategory(categoryEnemy);
enemy.setCollidesWith([categoryPlayer, categoryPlatform]);State Machine for Character Movement
Use the state pattern to manage complex movement behaviors:
interface State {
enter(player: Player): void;
update(player: Player, delta: number): void;
exit(player: Player): void;
}
class IdleState implements State {
enter(player: Player) {
player.setVelocityX(0);
player.play('idle');
}
update(player: Player, _delta: number) {
if (player.cursors.left.isDown || player.cursors.right.isDown) {
player.stateMachine.transition('walk');
}
if (player.cursors.up.isDown && player.isGrounded()) {
player.stateMachine.transition('jump');
}
}
exit(_player: Player) {}
}
class WalkState implements State {
enter(player: Player) {
player.play('walk');
}
update(player: Player, _delta: number) {
if (player.cursors.left.isDown) {
player.setVelocityX(-player.speed);
player.setFlipX(true);
} else if (player.cursors.right.isDown) {
player.setVelocityX(player.speed);
player.setFlipX(false);
} else {
player.stateMachine.transition('idle');
}
if (player.cursors.up.isDown && player.isGrounded()) {
player.stateMachine.transition('jump');
}
}
exit(_player: Player) {}
}
class JumpState implements State {
enter(player: Player) {
player.setVelocityY(-player.jumpForce);
player.play('jump');
}
update(player: Player, _delta: number) {
// Air control
if (player.cursors.left.isDown) {
player.setVelocityX(-player.speed * 0.8);
} else if (player.cursors.right.isDown) {
player.setVelocityX(player.speed * 0.8);
}
if (player.isGrounded()) {
player.stateMachine.transition('idle');
}
}
exit(_player: Player) {}
}Simple State Machine Implementation
export class StateMachine {
private states = new Map<string, State>();
private currentState?: State;
private owner: Player;
constructor(owner: Player) {
this.owner = owner;
}
addState(name: string, state: State) {
this.states.set(name, state);
}
transition(name: string) {
const next = this.states.get(name);
if (!next) return;
this.currentState?.exit(this.owner);
this.currentState = next;
this.currentState.enter(this.owner);
}
update(delta: number) {
this.currentState?.update(this.owner, delta);
}
}Mobile-Aware State Machine
To make state machines work across keyboard and touch, abstract raw input into an inputState object. States receive this object and never read cursors directly:
// In Scene update() — build inputState from all sources
const inputState = {
left: this.cursors.left.isDown || this.wasd.left.isDown || this.touchLeft,
right: this.cursors.right.isDown || this.wasd.right.isDown || this.touchRight,
jump: Phaser.Input.Keyboard.JustDown(this.spaceKey) || this.touchJump,
};
this.player.stateMachine.update(delta, inputState);
// In states — use inputState instead of player.cursors
class WalkState implements State {
update(player: Player, delta: number, inputState: InputState) {
if (inputState.left) {
player.setVelocityX(-player.speed);
player.setFlipX(true);
} else if (inputState.right) {
player.setVelocityX(player.speed);
player.setFlipX(false);
} else {
player.stateMachine.transition('idle');
}
if (inputState.jump && player.isGrounded()) {
player.stateMachine.transition('jump');
}
}
}This pattern ensures states are input-source-agnostic. Adding a new input method (gamepad, tilt) only requires updating the inputState construction in the Scene, not every state.
Time-Based Movement
Always use delta for consistent movement across frame rates:
update(_time: number, delta: number) {
// delta is in milliseconds
const speed = 200; // pixels per second
const dx = speed * (delta / 1000);
this.player.x += dx;
}Or use Phaser's velocity system which handles this automatically:
this.player.setVelocityX(200); // Arcade physics handles delta internallyPlatformer Tips
- Set
player.body.setGravityY()for per-object gravity overrides - Use
body.blocked.downto check if grounded (Arcade) - Implement coyote time: allow jumping briefly after leaving a ledge
- Variable jump height: reduce Y velocity on key release
// Variable jump height
if (Phaser.Input.Keyboard.JustUp(this.cursors.up) && this.player.body!.velocity.y < 0) {
this.player.setVelocityY(this.player.body!.velocity.y * 0.5);
}Project Setup
Quick Start
npx degit phaserjs/template-vite-ts my-game
cd my-game
npm install
npm run devDirectory Structure
src/
├── scenes/
│ ├── Boot.ts # Minimal setup, start Game scene
│ ├── Preloader.ts # Load all assets, show progress bar
│ ├── Game.ts # Main gameplay (starts immediately, no title screen)
│ └── GameOver.ts # End screen with restart
├── objects/
│ ├── Player.ts # Custom game objects
│ └── Enemy.ts
├── systems/ # ECS systems or managers
│ ├── AudioManager.ts
│ └── SaveManager.ts
├── utils/
│ └── helpers.ts
├── config.ts # Phaser.Types.Core.GameConfig
└── main.ts # Entry point
assets/
├── images/
├── audio/
├── tilemaps/
└── atlases/ # Texture atlas JSON + PNGsGame Configuration
// src/config.ts
import Phaser from 'phaser';
import { Boot } from './scenes/Boot';
import { Preloader } from './scenes/Preloader';
import { Game } from './scenes/Game';
import { GameOver } from './scenes/GameOver';
export const config: Phaser.Types.Core.GameConfig = {
type: Phaser.AUTO,
width: 800,
height: 600,
parent: 'game-container',
backgroundColor: '#000000',
scale: {
mode: Phaser.Scale.FIT,
autoCenter: Phaser.Scale.CENTER_BOTH,
},
physics: {
default: 'arcade',
arcade: {
gravity: { x: 0, y: 300 },
debug: false,
},
},
scene: [Boot, Preloader, Game, GameOver],
};// src/main.ts
import Phaser from 'phaser';
import { config } from './config';
new Phaser.Game(config);TypeScript Configuration
The template provides a working tsconfig.json. Key settings:
{
"compilerOptions": {
"target": "ESNext",
"module": "ESNext",
"moduleResolution": "bundler",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true
},
"include": ["src"]
}Vite Configuration
// vite.config.ts
import { defineConfig } from 'vite';
export default defineConfig({
base: './',
build: {
rollupOptions: {
output: {
manualChunks: {
phaser: ['phaser'],
},
},
},
},
server: {
port: 8080,
},
});Splitting Phaser into its own chunk improves caching — the framework rarely changes between deploys.
Asset Pipeline
- Use TexturePacker or free-tex-packer to create atlases
- Export as JSON Hash format (Phaser's default atlas format)
- Place atlas JSON + PNG pairs in
assets/atlases/ - For audio, prefer
.ogg(wide support) with.mp3fallback
NPM Scripts
{
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview"
}
}Responsive Canvas Config (Retina/High-DPI)
For pixel-perfect rendering on any display, size the canvas to match the user's device pixel area (not a fixed base resolution). This prevents CSS-upscaling blur on high-DPI screens.
// Constants.ts
export const DPR = Math.min(window.devicePixelRatio || 1, 2);
const isPortrait = window.innerHeight > window.innerWidth;
const designW = isPortrait ? 540 : 960;
const designH = isPortrait ? 960 : 540;
const designAspect = designW / designH;
// Canvas = device pixel area, maintaining design aspect ratio
const deviceW = window.innerWidth * DPR;
const deviceH = window.innerHeight * DPR;
let canvasW, canvasH;
if (deviceW / deviceH > designAspect) {
canvasW = deviceW;
canvasH = Math.round(deviceW / designAspect);
} else {
canvasW = Math.round(deviceH * designAspect);
canvasH = deviceH;
}
// PX = canvas pixels per design pixel. Scale ALL absolute values by PX.
export const PX = canvasW / designW;
export const GAME = {
WIDTH: canvasW, // e.g., 3456 on a 1728×1117 @2x display
HEIGHT: canvasH,
GRAVITY: 800 * PX,
};
// GameConfig.ts
scale: {
mode: Phaser.Scale.FIT,
autoCenter: Phaser.Scale.CENTER_BOTH,
zoom: 1 / DPR,
},
roundPixels: true,
antialias: true,
// All absolute pixel values use PX (not DPR). Proportional values use ratios.
const groundH = 30 * PX;
const buttonY = GAME.HEIGHT * 0.55;Entity Sizing
Character dimensions must preserve their spritesheet aspect ratio across all orientations. Derive HEIGHT from WIDTH using the sprite's native aspect ratio (200×300 spritesheets = 1.5):
const SPRITE_ASPECT = 1.5;
// Good — HEIGHT derived from WIDTH, correct in both landscape and portrait
PLAYER: {
WIDTH: GAME.WIDTH * 0.08,
HEIGHT: GAME.WIDTH * 0.08 * SPRITE_ASPECT,
}
// Bad — independent GAME.HEIGHT ratio squishes characters in portrait mode
PLAYER: {
WIDTH: GAME.WIDTH * 0.08,
HEIGHT: GAME.HEIGHT * 0.12,
}
// Bad — fixed size regardless of screen
PLAYER: {
WIDTH: 40 * PX,
HEIGHT: 40 * PX,
}For character-driven games (named characters, personalities, mascots), make characters prominent — use 12–15% of GAME.WIDTH for the player width. Use caricature proportions (large head ~40–50% of sprite height with exaggerated features, compact body) for personality games to maximize character recognition at any scale. Never define character HEIGHT as GAME.HEIGHT * ratio — on mobile portrait, GAME.HEIGHT is much larger than GAME.WIDTH, breaking the aspect ratio and squishing heads vertically.
HTML boilerplate (required for proper scaling):
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
html, body { width: 100%; height: 100%; overflow: hidden; background: #000; }
#game-container { width: 100%; height: 100%; }
</style>Portrait-First Games
For vertical game types (dodgers, runners, collectors, endless fallers), force portrait mode regardless of device orientation. Set FORCE_PORTRAIT = true in Constants.js — this locks _isPortrait = true and uses fixed 540×960 design dimensions. On desktop, Scale.FIT + CENTER_BOTH automatically pillarboxes with black bars (no CSS changes needed when background: #000 is set on body).
// Constants.js — force portrait for vertical games
const FORCE_PORTRAIT = true;
const _isPortrait = FORCE_PORTRAIT || window.innerHeight > window.innerWidth;
const _designW = 540;
const _designH = 960;Without this, desktop browsers stretch the game to landscape, ruining the vertical layout. The template default is FORCE_PORTRAIT = false (auto-detect orientation).
Scenes & Lifecycle
Scene Lifecycle
init(data?) → preload() → create() → update(time, delta) [loop]
shutdown() [on scene stop/restart]| Method | Purpose |
|---|---|
init(data?) | Receive data from scene transitions. Reset state here. |
preload() | Load assets (prefer a dedicated Preloader scene instead). |
create() | Create game objects, set up physics, bind events. |
update(time, delta) | Game loop. Use delta for time-based movement. |
shutdown() | Clean up listeners, timers, tweens when scene stops. |
Basic Scene Template
import Phaser from 'phaser';
export class Game extends Phaser.Scene {
private player!: Phaser.Physics.Arcade.Sprite;
private cursors!: Phaser.Types.Input.Keyboard.CursorKeys;
constructor() {
super('Game');
}
init(data: { level: number }) {
// Receive data from scene transition
}
create() {
this.player = this.physics.add.sprite(400, 300, 'player');
this.cursors = this.input.keyboard!.createCursorKeys();
// Clean up on shutdown
this.events.on('shutdown', this.shutdown, this);
}
update(_time: number, delta: number) {
// Delegate to player's own update
this.handleInput(delta);
}
private handleInput(delta: number) {
const speed = 200;
if (this.cursors.left.isDown) {
this.player.setVelocityX(-speed);
} else if (this.cursors.right.isDown) {
this.player.setVelocityX(speed);
} else {
this.player.setVelocityX(0);
}
}
shutdown() {
// Remove event listeners to prevent memory leaks
this.events.off('shutdown', this.shutdown, this);
}
}Preloader Pattern
Load all assets in a single Preloader scene to avoid per-scene loading:
export class Preloader extends Phaser.Scene {
constructor() {
super('Preloader');
}
preload() {
// Progress bar
const bar = this.add.rectangle(400, 300, 0, 30, 0xffffff);
this.load.on('progress', (value: number) => {
bar.width = 400 * value;
});
// Load everything
this.load.atlas('sprites', 'assets/atlases/sprites.png', 'assets/atlases/sprites.json');
this.load.audio('bgm', ['assets/audio/bgm.ogg', 'assets/audio/bgm.mp3']);
this.load.tilemapTiledJSON('level1', 'assets/tilemaps/level1.json');
}
create() {
this.scene.start('Game');
}
}Scene Transitions
// Start a new scene (stops current)
this.scene.start('Game', { level: 1 });
// Launch a scene in parallel (overlay)
this.scene.launch('HUD');
// Pause/resume
this.scene.pause('Game');
this.scene.resume('Game');
// Stop a scene
this.scene.stop('HUD');
// Restart current scene
this.scene.restart({ level: 2 });Parallel Scenes (UI Overlay)
Run HUD as a separate scene on top of gameplay:
// In Game scene's create():
this.scene.launch('HUD');
// HUD scene listens for game events:
export class HUD extends Phaser.Scene {
private scoreText!: Phaser.GameObjects.Text;
constructor() {
super('HUD');
}
create() {
this.scoreText = this.add.text(16, 16, 'Score: 0', { fontSize: '24px' });
// Listen for score updates from Game scene
this.registry.events.on('changedata-score', (_: unknown, value: number) => {
this.scoreText.setText(`Score: ${value}`);
});
}
}Cross-Scene Communication
Registry (shared data store)
// Set in Game scene
this.registry.set('score', 100);
// Read in any scene
const score = this.registry.get('score');
// Listen for changes
this.registry.events.on('changedata-score', (_: unknown, value: number) => { ... });Game-level events
// Emit from any scene
this.game.events.emit('player-died', { lives: 2 });
// Listen in another scene
this.game.events.on('player-died', (data: { lives: number }) => { ... });Direct scene access (use sparingly)
const gameScene = this.scene.get('Game') as Game;Scene Sleep vs Stop
scene.sleep('Game')— Pauses update but keeps objects in memory. Fast resume.scene.stop('Game')— Destroys scene objects. Clean restart withscene.start().- Use sleep for scenes you'll return to frequently (e.g., pause menu).
Related skills
How it compares
Pick phaser when standardizing Phaser 3 atlas and performance patterns rather than general Canvas or PixiJS tutorials.
FAQ
What atlas format does phaser recommend?
phaser recommends exporting sprite atlases as JSON Hash from TexturePacker or free-tex-packer, then loading via this.load.atlas in Phaser 3 TypeScript.
Why use atlases in phaser skill examples?
phaser documents that individual this.load.image calls cost one draw call each, while a single atlas enables one draw call for many sprites, improving HTML5 game performance.
Is Phaser safe to install?
skills.sh reports 3 of 3 security scanners passed. Review the Security Audits panel on this page before installing in production.