Phaser

From PlayableIntelligence/game-creator · View interactive version

Phaser is an AI agent skill from the GitHub repository PlayableIntelligence/game-creator. Build 2D browser games with Phaser 3 using scene-based architecture and centralized state. Use when creating a new 2D game, adding 2D game features, working with Phaser, or building sprite-based web games.

How to use this skill

Skill file

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:

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 install

Required 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 point

See project-setup.md for full config and tooling details.

Scene Architecture

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:

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:

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,
};

See scenes-and-lifecycle.md for patterns and examples.

Game Objects

See game-objects.md for implementation patterns.

Physics

See physics-and-movement.md for details.

Performance (Critical Rules)

See assets-and-performance.md for full optimization guide.

Advanced Patterns

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)

Examples

Pre-Ship Validation Checklist

Before considering a game complete, verify:

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 |

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.