O'Reilly logo

Building HTML5 Games with ImpactJS by Jesse Freeman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Adding Grenade Explosions

Now that we have seen how to add death animations to our player and zombie, let’s look at how to make our grenades explode. Let’s add the following particle to our player.js module:

EntityGrenadeParticle = ig.Entity.extend({
    size: {x: 1, y: 1},
    maxVel: {x: 160, y: 200},
    lifetime: 1,
    fadetime: 1,
    bounciness: 0.3,
    vel: {x: 40, y: 50},
    friction: {x:20, y: 20},
    checkAgainst: ig.Entity.TYPE.B,
    collides: ig.Entity.COLLIDES.LITE,
    animSheet: new ig.AnimationSheet( 'media/explosion.png', 1, 1 ),
    init: function( x, y, settings ) {
        this.parent( x, y, settings );
        this.vel.x = (Math.random() * 4 - 1) * this.vel.x;
        this.vel.y = (Math.random() * 10 - 1) * this.vel.y;
        this.idleTimer = new ig.Timer();
        var frameID = Math.round(Math.random()*7);
        this.addAnim( 'idle', 0.2, [frameID] );
    },
    update: function() {
        if( this.idleTimer.delta() > this.lifetime ) {
            this.kill();
            return;
        }
        this.currentAnim.alpha = this.idleTimer.delta().map(
            this.lifetime - this.fadetime, this.lifetime,
            1, 0
        );
        this.parent();
    }
});

At this point, everything should look very familiar. We probably could have even extended our EntityDeathExplosionParticle but, to keep things simple, I just copied over the code and changed a few properties. Now we just need to spawn a few particles once the grenade explodes. Override the EntityGrenade kill() method with this code:

kill: function(){
    for(var i = 0; i < 20; i++)
        ig.game.spawnEntity(EntityGrenadeParticle, this.pos.x, this.pos.y);
    this.parent();
}

Refresh the game and fire a grenade. You should see a nice little particle explosion when it collides with anything or bounces too many times.

The grenade now explodes.

Figure 4-29. The grenade now explodes.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required