Ch021 - Polish: Explosions using Particles
Polish: Explosions using Particles
We are going to make our death more dramatic by using particles to make it look like our player explodes.

Check the Code: what we need to know and do
Adding an explsion uses the following knowledge which we covered in another chapter;
- Collision detection using overlap() function- see Adding a Reward
The code for a minimal example of the Explosions using Particles game polish element is shown here - https://jamm-labs.github.io/ggcp/add-polish-explosions-using-particles/game.js
Going over the code:
We make the explosion make it grey as a tribute to Nintendo’s censoring of Mortal Kombat turning red blood into grey sweat to make the violence less graphic!.
To do this we import an image of a grey pixel block and name it sweat which is used by a new function which sets up a “particle emitter”. These little blocks will be the particle explode out of this emitter.
var setParticles = function() {
sweat = game.add.emitter(0, 0, 20);
sweat.makeParticles('sweat');
sweat.setYSpeed(-150, 150);
sweat.setXSpeed(-150, 150);
sweat.gravity = 0;
};
This code creates a particle emitter, which is suitable as a base for our explosion. The values (0,0,20) mean that the explosion will start from the centre and and will have a maximum of 20 particle blocks in the explosion.
Add the following code at the start of the hitHazard function to start the explosion.
sweat.x = player.x;
sweat.y = player.y+10;
sweat.start(true, 300, null, 20);
This sets up where the explosion will happen, which is a bit above where the player is, and starts the process.
To make this work effectively in our game we will also need to replace the line calling restart(); in the hitHazard function with the following line to wait for one second before restarting the game.
game.time.events.add(1000, restart, this);
Understanding the code
start(true, lifespan=0, null, total) - true, means the emitter is an explosion type, 300 is how long it will last, null is if it will repeat so here it won’t it’s a one off, and 20 is the number of particles that will make up the explosion. .
There is full information in the documentation below:
https://photonstorm.github.io/phaser-ce/Phaser.Particles.Arcade.Emitter.html
https://photonstorm.github.io/phaser-ce/Phaser.Particles.Arcade.Emitter.html#start