phaserjs/phaser/groups-and-containers

Claude Code and agent skill by phaserjs/phaser

Trust tier 2
  • community
LLM review pending
Source check pending

Checking that the SKILL.md file is still in the repository.

Phaser 4 Groups, Containers and Layers: this.add.group (object pools with get, classType, maxSize, runChildUpdate, createMultiple, batch setters), this.add.container (children that move, rotate, scale and fade together, setSize for input, list order) and this.add.layer (render order buckets sorted by depth, with alpha, blend mode and filters). Use when pooling bullets or enemies, spawning many of the same object, building a HUD, a button, a health bar or other composite UI, moving a group of objects as one, or controlling what draws on top. Corrects v3 habits: Group has no setScale (use Phaser.Actions.SetScale), get() reuses a member without activating it, a Container ignores child depth, a Layer can't go in a Container, Layer is a real Game Object. Triggers on: Group, Container, Layer, object pool, bullet pool, get, getFirstDead, killAndHide, runChildUpdate, children, render order, draw order, HUD container.

Install

npx vskill@latest install phaserjs/phaser/groups-and-containers

SKILL.md

The same SKILL.md was published earlier as phaserjs/phaser/groups-and-containers.

Groups, Containers and Layers

Three ways to collect Game Objects. A Group is a list with pooling. A Container is a parent with a transform. A Layer is a bucket that sets draw order.

Source: src/gameobjects/group/Group.js, src/gameobjects/group/typedefs/, src/gameobjects/container/Container.js, src/gameobjects/layer/Layer.js, src/actions/. Related: physics-arcade (physics groups), actions-and-utilities, cameras (HUD cameras), input-keyboard-mouse-touch.

Quick start

js
// Group: a pool of up to 30 bullets
const bullets = this.add.group({ defaultKey: 'bullet', maxSize: 30 });
// Container: a heart and a label which move together
const lives = this.add.container(20, 20, [
this.add.image(0, 0, 'heart'),
this.add.text(24, -10, 'x3')
]);
// Layers: everything in `ui` draws above everything in `world`
const world = this.add.layer();
const ui = this.add.layer();
world.add(this.add.image(0, 0, 'sky').setOrigin(0));
ui.add(lives);
GroupContainerLayer
DrawnNo: its members are drawn by the Scene, one by oneYes, it draws its childrenYes, it draws its children
Position, rotation, scaleNoYes, children inherit themNo
Alpha, visible, blend modeBatch setters on the membersYes, for all childrenYes, for all children
Child draw orderNot a draw orderList order. Child depth is ignoredSorted by depth
Object in more than oneYesNo, by defaultNo
Pooling and runChildUpdateYesNoNo
InputOn membersYes, after setSizeNo

Groups and pools

js
class Bullet extends Phaser.GameObjects.Image
{
constructor (scene, x, y)
{
super(scene, x, y, 'bullet'); // the Group adds it to the Scene
}
fire (x, y)
{
this.setPosition(x, y).setActive(true).setVisible(true);
}
update (time, delta)
{
this.y -= 0.6 * delta;
if (this.y < -20)
{
this.setActive(false).setVisible(false); // back in the pool
}
}
}
// In create:
this.bullets = this.add.group({ classType: Bullet, maxSize: 30, runChildUpdate: true });
// To fire:
const bullet = this.bullets.get();
if (bullet) // null when all 30 are in use
{
bullet.fire(this.scale.width / 2, this.scale.height - 50);
}
  • get(x, y, key, frame, visible) returns the first inactive member, or makes a new one if the Group isn't full, or returns null. A reused member only has its x and y set: it's still inactive and maybe hidden, so always call setActive(true) and setVisible(true).
  • runChildUpdate: true calls update(time, delta) on every active member, each frame.
  • classType defaults to Phaser.GameObjects.Sprite, and is made with new classType(scene, x, y, key, frame). defaultKey and defaultFrame are used when get or create aren't given a key.
  • getFirstDead(createIfNull, x, y), getFirstAlive(), getFirst(active, createIfNull, ...), getLast(...), countActive(true), getTotalUsed(), getTotalFree(), isFull().
  • kill(obj) sets it inactive. killAndHide(obj) also hides it. Neither removes it from the Group.
  • For a pool with Arcade bodies use this.physics.add.group({ classType, maxSize }) and enableBody / disableBody, because killAndHide leaves the body colliding. See physics-arcade.
Making members
js
const coins = this.add.group({
key: 'coin',
quantity: 12,
setXY: { x: 100, y: 200, stepX: 64 },
setScale: { x: 0.5, y: 0.5 }
});
  • With no key, nothing is made. key alone makes one. repeat: 4 makes 5, and quantity sets the number directly.
  • The same keys work in group.createMultiple(config), which also takes an array of configs. Others: frame, setRotation, setOrigin, setAlpha, setDepth, setScrollFactor, gridAlign. gridAlign is applied after setXY and replaces its positions. All are in src/gameobjects/group/typedefs/GroupCreateConfig.js.
  • create(x, y, key, frame, visible, active) makes one member and adds it to the Scene. add(obj, addToScene = false) adds an existing one. this.add.group([ a, b, c ]) makes a Group of existing objects.
  • remove(obj, removeFromScene = false, destroyChild = false), clear(removeFromScene, destroyChild), destroy(destroyChildren = false). A destroyed member leaves the Group by itself.
Changing every member
js
const coins = this.add.group({ key: 'coin', quantity: 12 });
coins.setXY(100, 200, 64, 0); // sets: 100, 164, 228, ... the last two are steps
coins.incX(10); // adds 10 to each x
coins.angle(15); // adds 15 degrees to each
coins.setAlpha(0.5);
coins.setVisible(false);
coins.setDepth(10);
coins.playAnimation('spin');
Phaser.Actions.SetScale(coins.getChildren(), 2); // Groups have no setScale
  • setX, setY, setXY, setAlpha, setDepth, setOrigin, setTint, setBlendMode, setVisible set values. incX, incY, incXY, angle, rotate, scaleX, scaleY, scaleXY add to them.
  • group.setActive() and group.setName() set the Group's own properties, not the members'. An inactive Group doesn't run runChildUpdate.
  • getChildren() returns the members as an array. They are stored in a Set, so there's no index. getMatching('active', true) filters them.
  • shuffle() changes the members' order. It did nothing before 4.3.
  • For anything else, use Phaser.Actions on group.getChildren(). See actions-and-utilities.

Containers

js
const { width, height } = this.scale;
const button = this.add.container(width / 2, height / 2);
const bg = this.add.rectangle(0, 0, 220, 64, 0x3355ff);
const label = this.add.text(0, 0, 'Play', { fontSize: '28px' }).setOrigin(0.5);
button.add([ bg, label ]);
button.setSize(220, 64); // the hit area, centred on the Container's position
button.setInteractive({ useHandCursor: true });
button.on(Phaser.Input.Events.GAMEOBJECT_POINTER_OVER, () => bg.setFillStyle(0x5577ff));
button.on(Phaser.Input.Events.GAMEOBJECT_POINTER_OUT, () => bg.setFillStyle(0x3355ff));
button.on(Phaser.Input.Events.GAMEOBJECT_POINTER_UP, () => this.scene.start('Game'));
  • Children are placed relative to the Container's position, and take its rotation, scale, alpha and visibility. Containers nest.
  • add takes the child off the Scene's display list. remove(child, destroyChild = false) puts it back. Destroying a Container destroys its children.
  • A Container has no size until setSize(w, h), which it needs for setInteractive(). The hit area is centred on the Container's x and y.
  • getAt(i), getByName(name), getAll(prop, value), count(prop, value), getIndex(child), exists(child), length, each(fn), iterate(fn). each and iterate pass only the child, not its index.
  • pointToContainer(worldPoint) converts a world point into the Container's local space.
  • A child can be in one Container at a time. Adding it to another moves it, unless setExclusive(false).
  • A Layer can't go in a Container: add throws. A Container can go in a Layer.
Draw order in a Container

Children draw in list order, first to last. A child's depth does nothing until you sort:

js
const container = this.add.container(400, 300);
const enemy = this.add.sprite(0, 0, 'enemy');
container.add([ enemy, this.add.sprite(20, 0, 'shield') ]);
enemy.setDepth(5);
container.sort('depth'); // now the enemy draws above the shield

Or move children directly: bringToTop(child), sendToBack(child), moveUp(child), moveDown(child), moveAbove(child, other), moveBelow(child, other), moveTo(child, index), or child.setToTop().

HUD in a Container

hud.setScrollFactor(0) keeps a Container still on screen. Children which take input need their own scroll factor too, as hit tests use it:

js
const hud = this.add.container(16, 16, [ this.add.text(0, 0, 'Score: 0') ]);
hud.setScrollFactor(0);
hud.each((child) => child.setScrollFactor(0));

hud.setScrollFactor(0, 0, true) is meant to do both, but in 4.3 it misses children whose scroll factor was never set. A HUD on a zooming camera also needs its own camera: see cameras.

Physics in a Container

An Arcade body on a child of a Container works while the Container isn't rotated or scaled. Otherwise put the body on the Container itself: container.setSize(w, h), then this.physics.add.existing(container).

Fixed in 4.3
  • A Container with filters and a scroll factor other than 1, such as a HUD, drew its filtered children in the wrong place when the camera scrolled.
  • A DOMElement in a rotated Container rotated around the wrong point, and a DOMElement with an origin drifted when the camera was zoomed.
  • A Container nested in another Container could take the blend mode of a sibling.

Layers

A Layer sorts its children by depth, like the Scene, and draws them as one unit. Use it to keep groups of objects above or below each other, whatever order they're made in.

js
const background = this.add.layer();
const actors = this.add.layer();
const ui = this.add.layer();
ui.add(this.add.text(16, 16, 'Score: 0'));
actors.add(this.add.sprite(200, 300, 'player'));
background.add(this.add.image(0, 0, 'sky').setOrigin(0)); // still drawn under the player
actors.setAlpha(0.8);
ui.setVisible(false);
  • Layers draw in the Scene's order: by depth, then by the order they were added. A child's depth only orders it within its Layer.
  • A Layer has alpha, blend mode, depth, visibility and a Canvas mask. It has no position, scale, rotation, scroll factor, input or physics.
  • layer.enableFilters() (WebGL only) applies filters to the whole Layer. See filters-and-postfx.
  • Layers nest, and can hold Containers.
  • camera.ignore(layer) hides the Layer and everything added to it later. That makes Layers the easy way to split a HUD from the world across two cameras.
  • Since 4.3, a Layer extends GameObject: layer instanceof Phaser.GameObjects.GameObject is true, and layer instanceof Phaser.Structs.List is false, though it still has the List methods.
  • Destroying a Layer destroys its children.

Gotchas

  • A Group isn't drawn and has no position. Changing a Group's x moves nothing. Use a Container, or the batch setters.
  • Reused pool members aren't active. get() only sets x and y on a member it reuses.
  • Members of a Container or Layer aren't on the Scene's display list. this.children.getChildren() doesn't list them.
  • Containers cost more than Layers. Each child's transform is combined with the Container's every frame. Use a Layer when you only need draw order, alpha or visibility.

Security

  • Security scanPassed, 100 of 100Pattern checks on the skill's files.
  • Model reviewNot runA model review is scheduled for the next rescan.

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

Repository stars
39,803
Repository forks
7,142
7-day trend score
53

Stars and forks are for the whole GitHub repository, not this skill alone. Not refreshed yet.

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Grok Build (Cursor)
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/phaserjs/phaser/groups-and-containers/badge)](https://verified-skill.com/skills/phaserjs/phaser/groups-and-containers)

Something wrong with this skill or its page? Tell us.