Object Pooling Example in Phaser

Scuba Chibi is potentially endless, so if I’m up to 120 points or so, I could experience lots of lag if I don’t use object pooling. It’s because I’m doing a lot of creating and deleting of objects (i.e. the enemies), and that wastes memory. This is a situation when object pooling becomes useful, so that I just deactivate objects that aren’t used and then reactivate them when they need to be reused. http://en.wikipedia.org/wiki/Object_pool_pattern

So let’s make an object pool for enemies and have up to 10 enemies of one type on the screen at one time.

this.enemyPool1 = [];
this.MAX_ENEMIES_PER_TYPE = 10;

Create all the enemies in the object pools, but deactivate them. Setting “obstacle.outOfBoundsKill = true;” means that the enemy will be deactivated when they go offscreen.

create: function() {
  var obstacle;

  // define obstacle group
  this.obstacles = game.add.group();
  this.obstacles.enableBody = true;
  this.obstacles.physicsBodyType = Phaser.Physics.ARCADE;

  // create enemy object pools and deactivate enemies
  for (i = 0; i < this.MAX_ENEMIES_PER_TYPE; i++) {
    obstacle = this.obstacles.create(-1000, -1000, 'enemy1');
    obstacle.checkWorldBounds = true;
    obstacle.outOfBoundsKill = true;
    obstacle.kill();
    this.enemyPool1.push(obstacle);
  }
}

Activate an enemy.

addObstacle: function(x, y, type) {
  var obstacle,
    i = 0;
  if (type === 1) {
    for (i = 0; i < this.enemyPool1.length; i++) {
      if (!this.enemyPool1[i].alive) {
         obstacle = this.enemyPool1[i];
         obstacle.reset(x, y);
         return obstacle;
      }
    }
  }
  return obstacle;
}

So basically, a couple of important functions in Phaser for object pooling are:

sprite.kill(); // halts rendering, but the object still exists
sprite.reset(); // reactivates the object so that it renders again and you can interact with them

One thought on “Object Pooling Example in Phaser”

Leave a Reply

Your email address will not be published. Required fields are marked *