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

phaser-arcade-physics — скилл для Claude Code: суть и установка

Настраивает перемещение, прыжки и столкновения в 2D-играх на Phaser 4 через физический движок Arcade Physics. Помогает писать контроллеры и собирать группы объектов.

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

Что делает phaser-arcade-physics

Направляет агента при работе с Arcade Physics в Phaser 4 с прицелом на версию 4.2. Помогает создавать динамические и статические тела через this.physics.add.sprite и staticGroup, задавать гравитацию, скорость и ускорение. Также скилл описывает связывание объектов через методы collider и overlap. Базовую настройку сцен и загрузку ресурсов скилл оставляет для phaser-core, а шарниры и составные тела — для Matter physics.

В инструкциях собраны частые ошибки движка. Менять координаты x и y напрямую опасно: тело начнёт проваливаться сквозь препятствия. Чтобы диагональный бег не ускорял персонажа, вектор скорости нормализуют. Проверка касания земли body.onFloor() сработает только при включённой гравитации и настроенном коллайдере с платформами.

Движок поддерживает только прямоугольники AABB и окружности. Из-за этого для сложных полигонов или реалистичных сочленений физика Arcade не подойдёт.

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

  • настроить перемещение игрока с нормализацией скорости по диагонали
  • реализовать механику прыжка в платформере с проверкой контакта через onFloor()
  • создать пул пуль через группу this.physics.add.group с повторным использованием
  • разделить обработку столкновений через collider и сбор бонусов через overlap

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

  • Сделай платформер на Phaser 4: добавь игрока, гравитацию и проверку прыжка на земле
  • Настрой движение персонажа для top-down игры в Phaser с помощью Arcade Physics и нормализацией скорости
  • Создай пул пуль через this.physics.add.group и настрой столкновения с врагами

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

1Через Skills CLI (Vercel)

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

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

~/.claude/skills/phaser-arcade-physics/SKILL.md

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

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

Вопросы о phaser-arcade-physics

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

Выполните команду npx skills add gamedev-skills/awesome-gamedev-agent-skills --skill phaser-arcade-physics -a claude-code.

Что делает скилл phaser-arcade-physics?

Он предоставляет правила работы с движком Arcade Physics в Phaser 4.2: настройка гравитации, групп, скоростей и обработка столкновений без проваливания сквозь стены.

В чём разница между collider и overlap в Arcade Physics?

Метод collider разделяет объекты и не даёт им проходить сквозь друг друга. Метод overlap только фиксирует факт пересечения и вызывает коллбэк, что подходит для сбора предметов и зон-триггеров.

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

SKILL.md · Apache-2.0
---
name: phaser-arcade-physics
description: >
  Use Phaser 4 Arcade Physics: enable the world, give sprites bodies, set
  velocity/acceleration/gravity, and resolve collisions with colliders, overlaps,
  groups, and world bounds. Use when a Phaser game needs movement or collisions —
  when the user mentions Arcade Physics, this.physics, setVelocity, collider,
  overlap, gravity, onFloor, or a platformer/top-down controller. For game config,
  scenes, and the loader use phaser-core.
---

# Phaser 4 Arcade Physics

Add movement and collision to a Phaser game with the lightweight **Arcade
Physics** engine (AABB rectangles and circles only). Targets **Phaser 4.2** for
new projects; inspect the installed major before editing an existing project.

## When to use

- Use for top-down or platformer movement, velocity/acceleration/gravity, bouncing,
  world bounds, and collision/overlap resolution between sprites, groups, and tiles.
- Use when the scene enables `physics: { default: 'arcade' }` and code calls
  `this.physics.add.*`, `body.setVelocity`, or `this.physics.add.collider`.

**When *not* to use:** the `Game` config, scene structure, asset loading, or
cameras → use `phaser-core`. Hinges, springs, complex polygons, or stacking
rigid bodies → use Matter physics (a different engine; Arcade and Matter bodies
do not interact). For engine-agnostic feel tuning see `physics-tuning`.

## Core workflow

1. **Enable the world.** Set `physics: { default: 'arcade', arcade: { gravity:
   {...}, debug: true } }` in the game or scene config. Turn `debug` on while
   building to see body outlines and velocity vectors.
2. **Give a sprite a body.** Create it with `this.physics.add.sprite(...)` (dynamic)
   or `this.physics.add.staticImage(...)` (static), or attach to an existing object
   with `this.physics.add.existing(obj)`.
3. **Drive it through the body, not by setting `x`/`y`.** Use `setVelocity`,
   `setAcceleration`, gravity, `setBounce`, and `setCollideWorldBounds`. The engine
   integrates position from velocity each step (already frame-rate independent).
4. **Resolve interactions.** `this.physics.add.collider(a, b)` separates bodies;
   `this.physics.add.overlap(a, b, cb)` detects without separating (pickups,
   triggers). Pass a callback to react.
5. **Group many objects.** Use `this.physics.add.group()` (dynamic) or
   `staticGroup()` (platforms) so one collider call handles all members.
6. **Check ground contact** with `body.onFloor()` / `body.blocked.down` before
   jumping. Run with `debug: true` and confirm bodies, contacts, and bounds.

## Patterns

### 1. Enable Arcade Physics (game config)

```js
const config = {
  type: Phaser.AUTO,
  width: 800, height: 600,
  physics: {
    default: 'arcade',
    arcade: {
      gravity: { x: 0, y: 600 },  // top-down? use { x: 0, y: 0 }
      debug: false                // true to draw bodies + velocity while building
    }
  },
  scene: [PlayScene]
};
new Phaser.Game(config);
```

### 2. Top-down movement (velocity from input)

```js
create() {
  this.player = this.physics.add.sprite(400, 300, 'player');
  this.player.setCollideWorldBounds(true);
  this.cursors = this.input.keyboard.createCursorKeys();
}

update() {
  const speed = 220;
  const body = this.player.body;
  body.setVelocity(0);                              // reset each frame
  if (this.cursors.left.isDown)  body.setVelocityX(-speed);
  if (this.cursors.right.isDown) body.setVelocityX(speed);
  if (this.cursors.up.isDown)    body.setVelocityY(-speed);
  if (this.cursors.down.isDown)  body.setVelocityY(speed);
  body.velocity.normalize().scale(speed);           // keep diagonals same speed
}
```

### 3. Platformer jump (gravity + ground check)

```js
create() {
  this.player = this.physics.add.sprite(100, 450, 'player');
  this.player.setCollideWorldBounds(true);

  // Static platforms: one body each, never moved by collisions.
  this.platforms = this.physics.add.staticGroup();
  this.platforms.create(400, 568, 'ground');
  this.physics.add.collider(this.player, this.platforms);

  this.cursors = this.input.keyboard.createCursorKeys();
}

update() {
  const onGround = this.player.body.blocked.down; // or this.player.body.onFloor()
  if (this.cursors.left.isDown)  this.player.setVelocityX(-160);
  else if (this.cursors.right.isDown) this.player.setVelocityX(160);
  else this.player.setVelocityX(0);

  if (this.cursors.up.isDown && onGround) this.player.setVelocityY(-450);
}
```

### 4. Colliders vs overlaps (separate vs detect)

```js
// Push apart and react: player vs enemies.
this.physics.add.collider(this.player, this.enemies, (player, enemy) => {
  this.handleHit(player, enemy);
});

// Detect without pushing: collect coins. The 4th arg is an optional
// process callback returning a boolean to filter pairs before the main callback.
this.physics.add.overlap(this.player, this.coins, (player, coin) => {
  coin.disableBody(true, true);              // deactivate + hide
  this.registry.inc('score', 10);
});
```

### 5. A group of moving objects

```js
this.bullets = this.physics.add.group({
  defaultKey: 'bullet',
  maxSize: 30                  // pool size; reuse instead of allocating
});

fire(x, y) {
  const bullet = this.bullets.get(x, y);     // reuses an inactive bullet if available
  if (!bullet) return;                       // pool is full: every bullet is active
  bullet.enableBody(true, x, y, true, true);
  bullet.setVelocityY(-500);
}

update() {
  // Return off-screen bullets to the pool, or firing stops after 30 shots.
  this.bullets.getChildren().forEach((bullet) => {
    if (bullet.active && bullet.y < -32) bullet.disableBody(true, true);
  });
}
```

## Pitfalls

- **Sprite ignores physics** → it was added with `this.add.sprite` instead of
  `this.physics.add.sprite` (or `this.physics.add.existing(obj)`), so it has no body.
- **Setting `sprite.x` directly fights the engine** → move dynamic bodies with
  `setVelocity`/`setAcceleration`. Direct position writes can tunnel through colliders.
- **Diagonal movement is faster** → independent X and Y velocities add up; normalise
  the velocity vector and rescale to the intended speed.
- **Platforms get pushed by the player** → use a `staticGroup`, or set
  `body.setImmovable(true)` on a dynamic platform.
- **`onFloor()` is always false** → the body needs something to collide with; add the
  `collider` against the ground/platforms before checking, and ensure gravity is on.
  Standing on an ordinary dynamic body does not count as blocked; make platforms
  static, immovable, or non-pushable (`platform.setPushable(false)`).
- **Moved a static body but collisions are stale** → static bodies don't auto-sync;
  call `body.updateFromGameObject()` (or `refreshBody()` on the game object).
- **Collider added every frame** → register `collider`/`overlap` once in `create`,
  not in `update`.
- **Fast bullets pass through thin walls** → Arcade has no swept collision; a body
  that moves farther than a wall's thickness in one physics step skips it. Thicken
  the wall's body, cap speed with `setMaxVelocity`, or raise the step rate
  (`arcade: { fps: 120 }`, default 60) at extra CPU cost.
- **Bodies pass through each other after adding collision categories** → a pair only
  collides when each side's mask includes the other's category, and untouched bodies
  keep mask `1`. Widen the other side's mask too, and set groups and their members
  separately (see the reference).
- **Drag does nothing while a key is held** → Arcade applies drag only on an axis
  with zero acceleration; set the acceleration to 0 when input stops.

## References

- For body anatomy and tuning (drag, bounce, max velocity, custom `setSize`/
  `setCircle`/`setOffset` hitboxes, collision categories/masks, and `worldbounds`
  events), read `references/bodies-and-collision.md`.

## Related skills

- `phaser-core` — game config, scenes, loader, cameras (the prerequisite setup).
- `physics-tuning` — engine-agnostic feel (fixed timestep, tunneling, jitter).
- `platformer` / `tower-defense` — genres that compose this skill.
- `level-design` — laying out tile/platform geometry these bodies collide with.

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

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

Всё по теме «Геймдев и 3D: Unity, Unreal, Godot, Blender» →
physics-arcade phaserjs Скилл для работы с Arcade Physics в Phaser 4: настройка физического мира, скорость и ускорение тел, гравитация, обнаружение столкновений и перекрытий. Нужен, чтобы ИИ-помощник помогал с динамикой объектов в играх. CX Codex +1 857установок physics-matter phaserjs Скилл учит ИИ настраивать физику Matter.js в Phaser 4: твёрдые тела, ограничения, сенсоры и перетаскивание объектов мышью. CX Codex +1 758установок godot-2d-physics thedivergentai Скилл с правилами и паттернами 2D-физики Godot для ИИ-агентов. Помогает настраивать слои коллизий, рейкасты и запросы к пространству без багов синхронизации. CX Codex +1 516установок phaser OpusGameLabs Скилл задаёт агенту структуру проекта для 2D-игр на Phaser 3: сцены, общий стейт, шина событий. Пригодится, когда начинаете новую игру или добавляете в неё механики. CX Codex +1 1 400установок add-feature OpusGameLabs Добавляет игровую механику в браузерную игру на Three.js или Phaser. Пригодится, когда нужно внедрить бонусы, комбо или двойной прыжок без поломки архитектуры проекта. CX Codex +1 977установок Gravity Shift: Low-Poly Physics Platformer loshu2000 Промпт описывает концепцию и техническую часть 3D-платформера, где мир поворачивается на 90 градусов по нажатию клавиши. Пригодится, если нужен стартовый каркас игры на Three.js и Cannon.js. GP ChatGPT ★ 174 597звёзд репо

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

unity-physics Помогает настроить 3D-физику в Unity 6.3 LTS: движение через Rigidbody, рейкасты, триггеры и слои коллизий. Пригодится при написании скриптов перемещения и проверок сцены. CX Codex +1 5 600установок roblox-datastores Учит агента сохранять данные игрока в Roblox через DataStoreService: загрузка на входе, сохранение на выходе и в BindToClose, ретраи. Пригодится, когда прогресс теряется. CX Codex +1 5 700установок unity-input-system Скилл для Claude Code, который настраивает ввод в Unity 6.3 LTS через Input System: action maps, PlayerInput, чтение значений в C#. CX Codex +1 5 700установок unity-scriptableobjects Помогает проектировать архитектуру данных в Unity 6.3 LTS на базе ScriptableObject. Настраивает общие переменные, каналы событий и реестры без менеджеров-одиночек. CX Codex +1 5 700установок threejs-scene-setup Настраивает базовую сцену three.js и помогает найти причины пустого или чёрного canvas. Нужен при старте проекта, ресайзе, цикле рендеринга и OrbitControls. CX Codex +1 5 500установок threejs-materials-lighting Скилл для three.js: подбирает материал, ставит источники света, включает тени и подключает HDR-окружение, когда модель выглядит чёрной или плоской. CX Codex +1 5 500установок unity-build-pipeline Автоматизирует сборку плееров в Unity 6.3 LTS через BuildPipeline, профили сборки и консольный CI-режим. Помогает выбрать бэкенд и урезать размер билда. CX Codex +1 5 600установок pixijs-rendering Скилл для сборки слоя рендера на PixiJS v8: асинхронный Application, загрузка текстур, сцена на Container, тикер и события указателя. CX Codex +1 5 400установок

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

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