Phaser Ripple Animation
I recently needed a ripple animation for a background effect in a game I was putting together. The simplest thing would be to use a sprite sheet. After a few hours of looking and not finding, I decided to code the animation using Phaser’s graphics. Yes, I know that putting together a ripple sprite sheet is not a great artistic task, but trust me, it is beyond my poor drawing abilities.
Anyway, this is what I came up with. An object(Ripple) that draws and redraws an ellipse and then after it fades, destroys itself. I then made another object (Ripples) that adds a ripple every 1 second. Here is the result:
The Code:
How to use
//turn the stage blue game.stage.backgroundColor = 0x43A8BB; //make the ripples this.ripples = new Ripples(); //place the ripples this.ripples.y = game.height * .6; this.ripples.x = game.width / 2;
Ripple.js
class Ripple extends Phaser.Group { constructor() { super(game); this.graphics = game.add.graphics(); //the elipse width this.ww = 1; //how much to speed up this.inc = 1; //add the graphics to the class this.add(this.graphics); //start the timer game.time.events.loop(Phaser.Timer.SECOND / 20, this.updateRipple, this); } drawRipple() { //height is 20% of the width this.hh = this.ww / 5; //set the thickness and color this.graphics.lineStyle(2, 0xffffff); //draw the elipse this.graphics.drawEllipse(0, 0, this.ww, this.hh); } updateRipple() { console.log("updateRipple"); //grow the ripple this.ww += this.inc; //turn down the alpha this.alpha -= .01; //clear the graphics this.graphics.clear(); this.drawRipple(); //if the alpha is faded enough //destroy the object if (this.alpha < .01) { this.destroy(true); } } }
Ripples.js
class Ripples extends Phaser.Group { constructor() { super(game); game.time.events.loop(Phaser.Timer.SECOND, this.addRipple, this); } addRipple() { var r=new Ripple(); this.add(r); } }