Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 36 ยท Sprites and Animation

Phaser Containers, Groups and Particle Emitters

Organize many game objects in Phaser: move them together with containers, manage collections with groups and object pools, and make effects with particle emitters.

A game scene quickly holds hundreds of objects: bullets, coins, enemies, clouds, sparks. You need ways to treat many objects as one: move a whole character made of several parts, update every enemy, reuse bullets instead of creating new ones, and spray hundreds of tiny sparks. Phaser gives you three tools for that: containers, groups and particle emitters.

Containers: objects that move together

A Container is a game object that holds other game objects. Its children use local coordinates, relative to the container's position. Move, rotate, scale or fade the container and all its children follow.

JavaScript
const hero = this.add.container(200, 150);       // x, y of the container
const body = this.add.rectangle(0, 0, 40, 60, 0x3b82f6);
const head = this.add.circle(0, -42, 16, 0xfcd34d);
hero.add([body, head]);                          // children at (0,0) and (0,-42) relative to hero

hero.x += 50;      // the whole figure moves
hero.angle = 20;   // the whole figure rotates

Containers are ideal for:

  • a character made of several pieces (body, weapon, shadow);
  • a button: background rectangle plus label;
  • a health bar: a frame, a fill and a text;
  • a menu panel you can slide in with a single tween.

Things to know:

  • Container children are drawn at the container's depth, in the order they were added. You cannot interleave them with outside objects.
  • The container has no size by default. Call container.setSize(w, h) before making it interactive, or enable physics.
  • Children have their own origin; the container's origin is always its top-left of the (zero-size) box.
  • Containers cost extra rendering work for each child, so do not nest deeply or use thousands of them. For many identical objects use groups, not containers.

Groups: collections you manage together

A Group is not a game object and is not drawn. It is a manager for a list of objects: a convenient way to say "all the enemies". You can loop over a group, apply a property to all members, check collisions against the whole group, and recycle members.

JavaScript
const coins = this.add.group();               // a plain group
const coin = coins.create(100, 100, 'coin');  // creates a sprite and adds it

const stars = this.add.group({
  key: 'star',
  repeat: 11,                                  // 1 + 11 = 12 stars
  setXY: { x: 20, y: 40, stepX: 40 }
});

stars.getChildren().forEach((star) => star.setTint(0xfacc15));

Common group methods:

Method Does
create(x, y, key) make and add a sprite
add(obj) / remove(obj, destroy) add or remove an existing object
getChildren() the array of members
getLength(), countActive() counts
getFirstDead(createIfNull, x, y, key) find an inactive member to reuse
killAndHide(obj) deactivate and hide a member for later reuse
clear(removeFromScene, destroy) remove everything
setAlpha, setTint, setDepth, ... apply a property to every member
maxSize the most members the group will hold (-1 means no limit)

In Phaser 3 tutorials you will see group.children.iterate(fn). In Phaser 4 a group's children are a plain JavaScript collection, so use group.getChildren().forEach(fn) (an ordinary array method) instead.

A Physics Group (this.physics.add.group()) does the same and gives every member an Arcade body. You will use physics groups for enemies and bullets.

Object pooling: do not create and destroy constantly

Creating and destroying objects is slow when done hundreds of times a second, because it allocates memory and the garbage collector later cleans up, which can cause tiny stutters. Pooling avoids it: make a fixed set of bullets once, then switch them on and off.

JavaScript
// create the pool once
this.bullets = this.physics.add.group({ defaultKey: 'bullet', maxSize: 20 });

// fire
fire(x, y) {
  const bullet = this.bullets.get(x, y);        // an inactive one, or a new one up to maxSize
  if (!bullet) return;                          // pool is empty: no shot
  bullet.setActive(true).setVisible(true);
  bullet.body.enable = true;
  bullet.setVelocityY(-400);
}

// recycle
update() {
  this.bullets.getChildren().forEach((b) => {
    if (b.active && b.y < -20) this.bullets.killAndHide(b);
  });
}

The pool never holds more than 20 bullets, so memory stays flat. When the pool is empty get returns null, which is a neat natural limit on the fire rate. The demo below pools "bubbles" and shows how many objects exist versus how many are active.

A pool of bubbles

Wait for a few seconds: the "created" number grows until 12 and then stays there, even though bubbles keep appearing. The pool recycles.

Containers in action

A container-based robot

The robot's parts never need absolute positions: they are relative to the container, and a single tween moves them all. The arm and the eyes still tween themselves inside the moving container.

Particle emitters

A particle emitter spawns many small, short-lived images and animates them according to rules: speed, direction, lifetime, size, color, fade. Fire, smoke, explosions, sparkles, rain and dust trails are all emitters. Particles are drawn very efficiently in bulk, so thousands are fine.

JavaScript
const emitter = this.add.particles(x, y, 'spark', {
  speed: { min: 60, max: 200 },
  angle: { min: 0, max: 360 },
  lifespan: 800,                          // ms
  scale: { start: 1, end: 0 },
  alpha: { start: 1, end: 0 },
  blendMode: 'ADD',                       // glowing
  gravityY: 200,
  frequency: 40,                          // one particle every 40 ms
  quantity: 2                             // two at a time
});

Three working modes:

  1. Continuous (frequency > 0): a steady stream, like a campfire.
  2. Explode: emitter.explode(30, x, y) emits 30 particles at once, then stops. Create the emitter with emitting: false and call explode on events (a coin pickup, an enemy hit).
  3. Follow: emitter.startFollow(sprite) makes the emitter track a moving object, for engine trails.

Other useful controls: emitter.stop(), start(), emitZone (spawn on a shape instead of one point), tint, rotate, and emitter.setPosition.

Sparks on click and a fire

Particles are cheap, but a burst of 40 every frame is not. Keep quantity, frequency and lifespan as low as the effect allows, and use the ADD blend mode for glow instead of many layers.

Choosing the right tool

flowchart TD
  A["Many objects"] --> B{"Do they move/rotate<br/>as one body?"}
  B -->|Yes| C["Container"]
  B -->|No| D{"Same kind, need<br/>collisions, loops, pooling?"}
  D -->|Yes| E["Group (physics group)"]
  D -->|No, lots of tiny<br/>visual effects| F["Particle emitter"]

Container for compound objects, group for collections, emitter for effects.

Common mistakes

  • Using a container for 500 coins. Use a group; containers render each child with extra work.
  • Calling group.create for every bullet. Pool them with maxSize and killAndHide.
  • Forgetting to re-enable a recycled physics body. Set body.enable = true and reset velocity.
  • Making a container interactive without setSize. It has no hit area until you give it a size.
  • Never destroying emitters. An emitter that has finished still exists; destroy it or reuse it.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What are the coordinates of a container's children relative to?

    Children are positioned relative to the container, so moving the container moves them all.
  2. 2. Is a Group a drawable game object?

    A Group has no position or visuals. It helps you loop over, configure and recycle its members.
  3. 3. What is the purpose of object pooling?

    A pool reuses a fixed set of objects, so frequent spawns (bullets, bubbles) do not allocate or garbage-collect.
  4. 4. How do you emit a one-time burst of 30 particles at a point?

    explode emits the given number of particles immediately. Create the emitter with emitting: false so it stays quiet otherwise.

Summary

  • A Container is a game object that moves, rotates and fades its children as one unit, using local coordinates.
  • A Group manages a collection (loop, configure, collide); with maxSize, get and killAndHide it becomes an object pool.
  • Particle emitters create many short-lived images for fire, sparks, smoke and trails; use continuous, explode or startFollow modes.
  • Pick containers for compound objects, groups for many similar objects and emitters for effects.

Next: Keyboard Input