Making a custom pool class by extending Phaser.Group

The Metroid HTML5 remake is written in ES6/ES2015 and transpiled to ES5 (today’s javascript standard). It’s less advanced than it might sound, especially when you can find boilerplates with task/build runners on Github doing all the work for you so that you can focus on your project. I’m using this excellent Phaser ES6 Boilerplat but there are a few to choose between. It comes with a Gulp-script that will listen to changes and build transpiled and concated versions of your code while working, plus serve it in a local server. The tutorial is still valid if you stick to ES5, but with a adjusted syntax.

Zoomers - Crawling Zebes since 1986.

Zoomers – Crawling Zebes since 1986.

Creating and destroying objects are quite expensive. Memory needs to be allocated for new objects, and their destruction will trigger the automatic garbage collector that may cause spikes in CPU usage. This might not be a problem if you’re creating a something like a board game. However, would you repeatedly create and destroy bullet sprite objects in a shoot ’em up with massive amounts of bullets, it would certainly affect the performance. The solution is called pools. Instead of destroying the objects, you just stuff it away until an object of the same type is needed again.

The Phaser.Group class can be used for various purposes like bulk actions (i.e. enabling gravity on all bodies in the group). It can also be used for pools. In the Metroid Remake, I use a custom pool class which is an extended Phaser.Group. All sprites, except Samus, is pooled. When an enemy is destroyed, its exists-property is just set to false, and when I need an enemy of the same kind I reset stuff like the health property and then I set the exists-property to true again.

As in my previous tutorial, I let the code do most of the explaining. Please note that this is a reduced part of the code I use in the Metroid Remake with the purpose to be as clear as possible. It’s not possible to “just run” the code. For instance, the spawn-function is a custom function described in my previous tutorial. Without actually creating a spawn function, the call will just generate an error.

So, now when we got a Pool class we can create new pools. This probably sits in a state’s create method:

All done! Let’s test the pools:

When you want to kill a sprite in a pool you just set its exists-property to false and it will be available for reuse in the pool. For the bullets, it would be when they hit something or goes off screen. For the enemies you might set the exist-property to false when the health property goes down to <=0.

I hope you have enjoyed this tutorial. If you have questions or remarks, please let me know in the comments. Thank you for reading.

Leave a Reply

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