К основному содержанию
скилл CX Codex

phaser-core — скилл для Claude Code: Phaser 4 с примерами

Скилл для настройки и отладки игр на Phaser 4: конфиг Game, жизненный цикл Scene (init/preload/create/update), загрузчик ассетов, камеры и передача данных между сценами. Пригодится, когда вы пишете или чините Phaser-игру.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add gamedev-skills/awesome-gamedev-agent-skills --skill phaser-core -a claude-code
Открыть на GitHub

Что делает phaser-core

Скилл охватывает всё ядро Phaser: от создания Phaser.Game с нужным конфигом до структурирования сцен, загрузки ассетов и переходов между экранами. Он различает Phaser 4.2 (для новых проектов) и Phaser 3.90 (не переписывает старые проекты). Внутри — паттерны для инициализации состояния в init(), очереди ассетов в preload(), использования кэша в create() и обновления логики в update(). Объясняет, как переключаться между сценами через start/launch/switch/sleep/wake, как делить состояние через this.registry и события сцен, как настроить камеру и что делать с кросс-сценовыми данными.

Для физики движения, столкновений и гравитации есть отдельный скилл phaser-arcade-physics. Если нужна жёсткая телесимуляция, это забота Matter Physics (другой инструмент). Для паттернов сохранения/загрузки ищите save-systems.

Скилл готов для Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI и OpenCode. Требует, чтобы в проекте уже стоял phaser в package.json.

Какие задачи решает

  • Настроить Game config и запустить первую сцену
  • Загрузить ассеты и использовать их в create/update
  • Переключаться между сценами и передавать данные
  • Отладить утечки состояния при перезапуске сцены
  • Синхронизировать HUD и игровую сцену через реестр

Примеры запросов агенту

  • Помоги создать новый Phaser 4 проект с Boot и Play сценами
  • Почему ассеты undefined в create? Я очередил их в preload
  • Как сделать, чтобы HUD сцена не перезапускалась каждый раз?

Как установить phaser-core

1Через Skills CLI (Vercel)

npx skills add gamedev-skills/awesome-gamedev-agent-skills --skill phaser-core -a claude-code

2Вручную: положить файлы

~/.claude/skills/phaser-core/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/phaser-core/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о phaser-core

Как установить phaser-core в Claude Code?

Выполните npx skills add gamedev-skills/awesome-gamedev-agent-skills --skill phaser-core -a claude-code, затем скилл появится в ~/.claude/skills/phaser-core/SKILL.md.

Что делает phaser-core?

Помогает настроить фундамент Phaser-игры: конфиг Game, жизненный цикл Scene, загрузку ассетов, камеры и передачу данных между сценами. Показывает паттерны и объясняет типичные ошибки.

Когда использовать phaser-core, а когда phaser-arcade-physics?

Используйте phaser-core для структуры сцен, загрузки ассетов и переходов между экранами. Для движения, столкновений, гравитации и перекрытий вызовите phaser-arcade-physics.

Исходный текст

SKILL.md · Apache-2.0
---
name: phaser-core
description: >
  Set up and debug a Phaser 4 game: the Game config, the Scene lifecycle
  (init/preload/create/update), the asset loader, cameras, and cross-scene
  communication. Use when building or debugging a Phaser game — when the user
  mentions Phaser, Phaser.Game, Phaser.Scene, preload/create/update, this.load,
  this.add, or scene transitions. For Arcade Physics movement/collisions use
  phaser-arcade-physics.
---

# Phaser 4 Core

Set up the foundation of a Phaser game: the `Game` config, the `Scene`
lifecycle, asset loading, cameras, and passing data between scenes. Targets
**Phaser 4.2** for new projects; keep an existing Phaser 3.90 project on its
pinned major unless the user explicitly asks for a migration.

## When to use

- Use when starting a Phaser game, wiring the `Phaser.Game` config, structuring
  `Scene`s, loading assets in `preload`, or fixing scene transitions and shared
  state.
- Use when the project has `phaser` in `package.json` or `import Phaser from 'phaser'`,
  and code uses `preload()`/`create()`/`update()`.

**When *not* to use:** movement, velocity, colliders, gravity, or overlap → use
`phaser-arcade-physics`. Complex rigid-body simulation uses Matter physics (a
separate concern). For cross-engine save/load patterns use `save-systems`.

## Core workflow

1. **Detect the installed major first.** Read `package.json` and the lockfile. Use
   Phaser 4.2 for new work; do not silently rewrite a Phaser 3 project as Phaser 4.
2. **Create the game from a config.** `new Phaser.Game(config)` with `type:
   Phaser.AUTO` (WebGL with Canvas fallback), a `width`/`height`, and a `scene`
   array. The first scene (and any with `active: true`) starts automatically.
3. **Model each screen as a `Scene`.** Subclass `Phaser.Scene`, pass a unique
   `key` to `super`, and implement the lifecycle: `init(data)` → `preload()` →
   `create(data)` → `update(time, delta)`.
4. **Load assets in `preload`, use them in `create`.** Queued assets are not
   available until `create`. The loader is per-scene; the cache it fills is global.
5. **Reset per-run state in `init()`, not the constructor.** A scene instance is
   reused across restarts, so constructor-set fields keep stale values.
6. **Move between screens** with `this.scene.start/launch/switch/sleep/wake`.
   Share data through `this.registry` (global) or a sibling scene's event emitter.
7. **Run and observe.** Serve the page, open it, and confirm assets load (watch the
   Network tab and console) and scenes switch as expected before assuming success.

## Patterns

### 1. Game config + boot (ES module)

```js
// main.js — one Game owns the renderer, loop, cache, and Scene Manager.
import Phaser from 'phaser';
import BootScene from './scenes/BootScene.js';
import PlayScene from './scenes/PlayScene.js';

const config = {
  type: Phaser.AUTO,            // WebGL if available, else Canvas
  width: 800,
  height: 600,
  backgroundColor: '#1d1d28',
  scale: { mode: Phaser.Scale.FIT, autoCenter: Phaser.Scale.CENTER_BOTH },
  scene: [BootScene, PlayScene] // BootScene starts first
};

new Phaser.Game(config);
```

### 2. A Scene with the full lifecycle

```js
// scenes/PlayScene.js
import Phaser from 'phaser';

export default class PlayScene extends Phaser.Scene {
  constructor() {
    super('play');                  // unique scene key
  }

  init(data) {
    // Reset run-specific state HERE so restarts start clean.
    this.score = 0;
    this.level = data.level ?? 1;
  }

  preload() {
    // Queue downloads. Not usable until create().
    this.load.image('player', 'assets/player.png');
    this.load.spritesheet('coin', 'assets/coin.png', { frameWidth: 16, frameHeight: 16 });
  }

  create() {
    this.player = this.add.sprite(400, 300, 'player');
    this.scoreText = this.add.text(10, 10, 'Score: 0', { fontSize: '20px', color: '#fff' });
    this.cursors = this.input.keyboard.createCursorKeys();
  }

  update(time, delta) {
    // delta is milliseconds since last frame; divide by 1000 for seconds.
    const speed = 200 * (delta / 1000);
    if (this.cursors.left.isDown)  this.player.x -= speed;
    if (this.cursors.right.isDown) this.player.x += speed;
  }
}
```

### 3. Cross-scene data + events

```js
// The registry is a global DataManager shared by every scene.
this.registry.set('coins', 0);                 // in any scene
const coins = this.registry.get('coins');      // read anywhere

// React to registry changes (e.g. a HUD scene listening to gameplay):
this.registry.events.on('changedata-coins', (parent, value) => {
  this.coinText.setText(`Coins: ${value}`);
});

// Talk directly to another running scene via its event emitter:
const ui = this.scene.get('hud');
ui.events.emit('show-message', 'Level cleared!');
```

### 4. Scene transitions (pick the right verb)

```js
this.scene.start('gameover', { score: this.score }); // stop this scene, start target
this.scene.launch('hud');        // run a second scene in parallel (restarts it if already running)
this.scene.run('hud');           // wake if sleeping, resume if paused, else (re)start
this.scene.bringToTop('hud');    // draw order follows the scene list, not launch order
this.scene.switch('menu');       // sleep this scene, start/wake target
this.scene.pause();              // freeze updates but keep rendering (modal)
this.scene.sleep();              // stop updating AND rendering, keep state for wake
```

### 5. A camera that follows the player

```js
this.cameras.main.setBounds(0, 0, 1600, 1200);  // world size
this.cameras.main.startFollow(this.player, true, 0.1, 0.1); // smooth lerp follow
this.cameras.main.setZoom(1.5);
```

## Pitfalls

- **Assets are `undefined` in `create`/`update`** → you forgot to queue them in
  `preload`, or used the wrong key. The loader runs between `preload` and `create`.
- **State leaks across a restart** → you set fields in the constructor. The Scene
  instance is reused; reset run state in `init()` and clear arrays on `shutdown`.
- **`this.scene.start` vs `this.scene.launch`** → `start` stops the calling scene;
  `launch` runs the target alongside it. Using `start` for a HUD hides the game.
- **HUD loses its state or draws behind the game** → `launch` (and `run`) on a scene
  that is already running shuts it down and starts it again; launch the HUD once, or
  guard with `if (!this.scene.isActive('hud'))`. Scenes draw in scene-list order, so a
  HUD listed before the gameplay scene renders underneath it until you call
  `this.scene.bringToTop('hud')`.
- **Scene state read right after `start`/`launch` is stale** → scene operations are
  queued and run at the start of the next game step, not synchronously.
- **`this` is wrong in a callback** → arrow functions keep the Scene's `this`; plain
  `function` callbacks need a context argument or `.bind(this)`.
- **Phaser 2 tutorials don't work** → "States" were renamed to "Scenes" in Phaser 3,
  and each Scene owns its own systems (input, cameras, tweens) rather than a global
  Game World.
- **Phaser 3 custom pipelines fail in Phaser 4** → Phaser 4 rebuilt the renderer and
  replaced the old FX/pipeline extension points. Migrate custom shaders and renderer
  plugins against the Phaser 4 guide; do not mechanically copy internal renderer code.
- **A Phaser 3 snippet runs but looks wrong in Phaser 4** → common renames: `preFX`/
  `postFX` and `BitmapMask` became filters (`obj.enableFilters()` then
  `obj.filters.internal`/`.external`); `setPipeline('Light2D')` became
  `setLighting(true)`; `setTintFill(c)` only logs an error, so use
  `setTint(c).setTintMode(Phaser.TintModes.FILL)`; `Phaser.Math.TAU` is now 2π (use
  `Phaser.Math.PI_OVER_2` where v3 code meant π/2); `Geom.Point` is gone (use
  `Phaser.Math.Vector2`). Canvas rendering still works but is deprecated.
- **Pixel art is blurry or shimmers while moving** → set `pixelArt: true` in the game
  config. It turns off antialiasing and turns on `roundPixels`, which defaults to
  `false` in Phaser 4.
- **Nothing renders / black screen** → confirm the canvas mounted, `width`/`height`
  are set, and a scene actually started (check `game.scene.dump()` output).
- **Two canvases (two games running) after a hot reload or a React/Vue remount** →
  a second `new Phaser.Game` ran while the first was still alive. Keep one instance
  and call `game.destroy(true)` when the host component unmounts; the teardown
  finishes on the next frame. Leave `noReturn` false, or no new game can start on
  the page.

## References

- For the full scene state machine (pause/resume vs sleep/wake vs stop/start, the
  restart-state bug, and removing/replacing scenes), read
  `references/scene-flow.md`.

## Related skills

- `phaser-arcade-physics` — velocity, gravity, colliders, overlap, and groups.
- `input-systems` — rebindable, multi-device input architecture (engine-agnostic).
- `pixijs-rendering` / `threejs-scene-setup` — other browser rendering stacks.
- `platformer` / `puzzle` — genre templates that compose Phaser skills.

© gamedev-skills · Apache-2.0 · gamedev-skills/awesome-gamedev-agent-skills

Похожие скиллы

Всё по теме «Геймдев и 3D: Unity, Unreal, Godot, Blender» →
phaser OpusGameLabs Скилл задаёт агенту структуру проекта для 2D-игр на Phaser 3: сцены, общий стейт, шина событий. Пригодится, когда начинаете новую игру или добавляете в неё механики. CX Codex +1 1 400установок sprites-and-images phaserjs Помогает создавать и настраивать объекты Sprite и Image в Phaser 4. Подсказывает правильные методы миксинов для позиционирования, масштабирования, кадров и обрезки текстур. CX Codex +1 1 100установок animations phaserjs Скилл для создания и управления спрайт-анимациями в Phaser 4. Охватывает загрузку спритшитов и атласов, создание анимаций через AnimationManager, воспроизведение, паузу, цепочки и события. CX Codex +1 1 100установок add-feature OpusGameLabs Добавляет игровую механику в браузерную игру на Three.js или Phaser. Пригодится, когда нужно внедрить бонусы, комбо или двойной прыжок без поломки архитектуры проекта. CX Codex +1 977установок phaser-2d-game официальный OpenAI Скилл помогает собирать 2D-игры для браузера на Phaser, TypeScript и Vite. Подходит для сцен, игровой логики, камер, анимации спрайтов и HUD. CX Codex GP ChatGPT 49установок game-studio официальный OpenAI Плагин для Codex и ChatGPT, который ведёт разработку браузерной игры: от прототипа до сборки, с ассетами и плейтестом. CX Codex GP ChatGPT ★ 7 596звёзд репо

Из того же набора77

godot-csharp Скилл для написания игр на C# в Godot 4.7 с поддержкой частичных классов, lifecycle-методов, Export-полей, сигналов как событий C# и взаимодействия с GDScript. Нужен Godot .NET build и .NET SDK 8+. CX Codex +1 5 900установок godot-multiplayer Настраивает сетевой мультиплеер в Godot 4.7 через ENet, аннотации @rpc, репликацию узлов и разграничение authority между сервером и клиентами. CX Codex +1 5 900установок steam-publish Скилл ведёт релиз игры в Steam по шагам: депоты и пакеты, загрузка через steamcmd, ветки, чек-листы ревью. Нужен, когда билд готов, а магазин и релиз ещё нет. CX Codex +1 5 900установок itch-publish Скилл проводит сборку игры до страницы на itch.io: butler push в нужный канал, версии, обновление только изменённых файлов. Пригодится, когда пора выложить демо или релиз. CX Codex +1 5 700установок game-jam Помогает спланировать разработку игры под дедлайн геймджема: распределить часы, урезать лишние механики и подготовить релиз к отправке. CX Codex +1 5 700установок unity-animation Ведёт агента по Animator Controllers в Unity 6.3 LTS: параметры, переходы, blend trees, слои и humanoid IK. Пригодится, когда один персонаж должен ходить, прыгать и целиться из общей стейт-машины. CX Codex +1 5 800установок threejs-gltf-loading Загружает glTF и GLB в three.js и проигрывает запечённые клипы через AnimationMixer, включая сжатые DRACO, Meshopt и KTX2. Пригодится, когда модель вроде загрузилась, а на экране пусто. CX Codex +1 5 600установок unity-physics Помогает настроить 3D-физику в Unity 6.3 LTS: движение через Rigidbody, рейкасты, триггеры и слои коллизий. Пригодится при написании скриптов перемещения и проверок сцены. CX Codex +1 5 600установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой