[Phaser]Rain and snow effects or how to use emitters

The atmosphere is an important touch in polishing one game and with Phaser game engine making rain and snow effects is relatively easy.  Phaser is HTML5 games framework with tons of documentation, examples and good mobile performance.  Here will look at rain and snow effects with the help of particles emitter.

How to use particle emitters?

Here is how you create basic emitter:

var emitter = game.add.emitter(game.world.centerX, 0, 200);

The parameters are – x, y and max particles. The field game.world.centerX provides the center of our game.

emitter.width = game.world.width;

This row will make our emitter add drops all over the game width.

At our preload function we need to load the image of a rain drop or a snowflake.

game.load.image('drop', 'assets/drop.png');

And then tell the emitter to use it for particles:

emitter.makeParticles('drop');

Starting the emitter with this:

emitter.start(false, 2500, 30, 0);

The first parameter of emitter.start if true will make the emitter burst the particles. We don’t want the burst effect so we set it to false. The second parameter is the lifespan of the particles. The third parameter tells the emitter to release one particle each 30ms. The forth parameter is quantity – how many particles will be emitter and if set to 0 the emitter will emit particles until max number of particles is reached.

The full code:

var game = new Phaser.Game(800, 500, Phaser.AUTO, null, { preload: preload, create: create});

function preload() {    
    game.load.image('drop', 'assets/drop.png');
}

function create() {
    game.stage.backgroundColor = "#3399bb";

    var emitter = game.add.emitter(game.world.centerX, 0, 200);

    emitter.width = game.world.width;

    emitter.makeParticles('drop');

    emitter.minParticleScale = 0.5;
    emitter.maxParticleScale = 1;

    emitter.setYSpeed(100, 300);
    emitter.setXSpeed(0);

    emitter.start(false, 2500, 30);
}

If we want to make realistic snow effect we must tweak the code above a bit. The snow is falling slower than rain so the y speed must be changed:

var game = new Phaser.Game(800, 500, Phaser.AUTO, null, { preload: preload, create: create});

function preload() {    
    game.load.image('snowflake', 'assets/snowflake.png');
}

function create() {
    game.stage.backgroundColor = "#3399bb";

    var emitter = game.add.emitter(game.world.centerX, 0, 200);

    emitter.width = game.world.width;

    emitter.makeParticles('snowflake');
   
    emitter.minParticleScale = 0.5;
    emitter.maxParticleScale = 1;

    emitter.setYSpeed(50, 200);
    emitter.setXSpeed(-30, 30);

    emitter.start(false, 3500, 30);
}

One comment

Leave a Reply

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