Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 36 ยท Game Architecture

Custom Game Objects and Object Pools

Organize Phaser code with custom classes that extend Sprite, give objects their own update logic and states, and reuse bullets with object pools.

Once a game has more than one kind of enemy, putting all behavior in the scene's update() method becomes a tangle of if statements and arrays. The fix is the same as in any object-oriented program: let each kind of thing be its own class. A Slime knows how to patrol, a Bullet knows how to fly and disappear, and the scene just creates them and wires up collisions.

Phaser is built for this. Its game objects are ordinary JavaScript classes that you can extend. This lesson shows how to write a custom sprite class, give it a small state machine, and then reuse objects with groups and object pools, so that a game that fires thousands of bullets does not create thousands of objects and make the garbage collector stutter.

Extending a game object

To make your own game object, extend the class you want and register the object with the scene in the constructor. Two calls are needed, and forgetting them is the usual first mistake:

JavaScript
class Coin extends Phaser.GameObjects.Sprite {
  constructor(scene, x, y) {
    super(scene, x, y, 'coin');
    scene.add.existing(this);          // puts it on the display list so it is drawn and updated
  }
}

scene.add.existing(this) adds the object to the scene's display and update lists. If you want physics, an Arcade body is added in the same way:

JavaScript
class Slime extends Phaser.Physics.Arcade.Sprite {
  constructor(scene, x, y) {
    super(scene, x, y, 'slime');
    scene.add.existing(this);
    scene.physics.add.existing(this);  // gives it this.body
  }
}

Phaser.Physics.Arcade.Sprite is a sprite that already has the physics helper methods (setVelocity, setBounce, setCollideWorldBounds). Extending it saves the this.body lookups.

Per-object update with preUpdate

A scene's update() runs once per frame, but objects can have their own per-frame code too. Sprites have a method called preUpdate(time, delta), which Phaser calls every frame for each active object that is on the display list. Override it to give the object its own behavior, and always call super.preUpdate(time, delta) first: the base class uses it to advance animations. Skipping the call freezes the object's animations without any error message.

JavaScript
preUpdate(time, delta) {
  super.preUpdate(time, delta);
  this.x += this.speed * delta / 1000;
}

Multiply by delta (milliseconds since the last frame) so that movement does not depend on the monitor's refresh rate.

A slime with a state machine

Most enemies are in one of a few modes at a time: patrol, chase, flee. A state machine keeps those modes separate and readable. The simplest version is a state string and one method per state, selected in preUpdate.

Enemy class with states

The class owns all of its own logic. The scene only creates three of them and moves the hero. Adding a second enemy type later means writing another class, with no change to Level. The state names double as method names (this[this.state]()), which is compact; for bigger enemies use a table of state objects with enter, update and exit functions.

Inheritance or composition?

Extending a class is not the only way to share behavior. If you find yourself building a deep chain (Enemy extends Mob extends Actor), consider composition: small helper objects that you attach to a sprite. A Health component with damage() and heal(), a Weapon with fire(), a Patrol behavior. Each is a plain class that receives its owner in the constructor. Different entities are then built by combining components, and you avoid forcing a flying enemy to inherit a walking method.

A reasonable rule: use inheritance one level deep (Phaser sprite to your entity class) and composition for everything that varies between entities.

Groups: collections of game objects

A group holds many game objects and treats them together. A group can apply an action to every member (group.setAlpha(0.5)), loop over members (getChildren(), children.iterate), count them (countActive()) and, importantly, serve as one side of a collision: this.physics.add.collider(player, enemyGroup) handles every enemy at once.

Groups can also create objects from a class you give them:

JavaScript
this.enemies = this.physics.add.group({ classType: Slime, runChildUpdate: false });
const slime = this.enemies.get(x, y);   // creates a Slime or reuses an inactive one

runChildUpdate: true makes the group call each member's update(time, delta) method (not preUpdate) every frame, which is handy for plain objects. For sprites you normally use preUpdate and leave it off.

Object pooling

Creating and destroying objects is not free. Every new Bullet() allocates memory and every destroy() leaves garbage that the JavaScript engine must collect later, which shows up as occasional frame drops. A game that spawns many short-lived objects (bullets, particles, floating damage numbers, hit sparks) should use a pool: create a fixed number of objects once, then switch them on and off.

Phaser groups implement this directly:

  • group.get(x, y, key) returns an inactive member if there is one, otherwise creates a new one (until maxSize is reached, after which it returns null).
  • You "free" an object with setActive(false).setVisible(false), or for physics objects disableBody(true, true), instead of destroy().
  • group.killAndHide(obj) does both steps for non-physics objects.
flowchart LR
  A["group.get()"] --> B{"Inactive object<br/>available?"}
  B -- yes --> C["Reuse it"]
  B -- no, below maxSize --> D["Create a new one"]
  B -- no, at maxSize --> E["Returns null:<br/>skip the shot"]
  C --> F["Object is used"]
  D --> F
  F --> G["Left the screen<br/>or hit something"]
  G --> H["Deactivate and hide<br/>(back to the pool)"]
  H --> A

Objects circulate between "in use" and "available" without ever being destroyed.

A bullet pool

Bullet pool

The scene fires 30 shots in about four seconds, and you can add your own by clicking. The text shows that the number of created bullets stays at a handful (it can never pass the maximum of 12), while the number in use goes up and down. Without a pool, 30 shots would create and destroy 30 objects; with one, a few objects are recycled.

Notes on the details:

  • enableBody(reset, x, y, enableGameObject, showGameObject) is the matching pair of disableBody(disableGameObject, hideGameObject). Use them rather than setActive for physics objects, so the body is removed from the physics world too.
  • cam.worldView.contains(x, y) tests whether a point is visible, which is the usual way to recycle off-screen bullets.
  • Returning null when the pool is empty is a design choice: a maximum fire rate. Some games prefer growing the pool; set maxSize: -1 (the default) to allow that.
  • Always reset all the state in the "fire" method (velocity, health, tint, animation). A recycled object keeps whatever it had last time, and forgotten state is the classic pooling bug.

What to pool

Pool anything that is created often and for a short time: projectiles, particle-like sprites, enemies in wave games, pickups, floating text. Do not bother pooling a player or a boss. Measure first: Phaser can create thousands of sprites per second, so pooling matters most on mobile or when you see periodic stutters caused by garbage collection.

Common mistakes

  • Missing scene.add.existing(this). The object exists but is never drawn.
  • Missing super.preUpdate(). Animations stop working.
  • Using destroy() inside a pooled object's update, then calling get() expecting it back. A destroyed object is gone for good.
  • Forgetting physics.add.existing and then using this.body, which is null.
  • Overriding a property that Phaser uses, such as this.state, this.body or this.scene. Phaser's GameObject already defines state (it is a free-use field, so our slime above is fine) but not scene or body; give your own fields distinctive names.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does scene.add.existing(this) do inside a custom sprite's constructor?

    Creating an object with new does not show it. add.existing registers it with the scene. Physics needs scene.physics.add.existing as well.
  2. 2. Why call super.preUpdate(time, delta) first when you override preUpdate in a sprite class?

    The Sprite base class updates its animation state in preUpdate. Without the super call the sprite's animations silently stop.
  3. 3. What is the main benefit of an object pool?

    Reusing a fixed set of objects avoids the memory churn that causes occasional frame drops.
  4. 4. With a pooled physics sprite, how do you return it to the pool when it leaves the screen?

    disableBody(true, true) removes the body from the physics world and deactivates and hides the object, so group.get can reuse it.
  5. 5. A recycled bullet sometimes flies at the wrong speed. What is the likely bug?

    A reused object keeps its previous values. Reset everything (velocity, health, tint, animation) when you activate it.

Summary

  • Extend Phaser.GameObjects.Sprite or Phaser.Physics.Arcade.Sprite for your own game objects, and call scene.add.existing(this) (plus scene.physics.add.existing(this) for a body).
  • Give each class its own preUpdate(time, delta) and call super.preUpdate first; a small state machine keeps behavior readable.
  • Prefer shallow inheritance and composition for behavior that varies between entities.
  • Groups manage collections, collisions and creation through classType.
  • Pools (group.get, maxSize, disableBody) reuse short-lived objects; reset all state when reusing.

Next: Events, Registry and Saving