Ch019 - Polish: Animate Sprite when Zapped
Polish: Animate Sprite when Zapped
Death and killing seem like strong words so let’s talk about getting zapped. Being zapped loses it’s sting when you can be reborn so easily. But to give the sense of dying rather than just disappearing we can add an animation to our player or enemy sprites so the gamer really know what is going on.
![]()
Check the Code: what we need to know and do
Better death here needs us to alter the function called when player and enemy overlaps. Let’s concentrate on animating the enemy, we need to change the sprite animation but also add a delay into the process of restarting the game so we can see the animation play out. The code for a minimal example of the Animate Sprite when Zapped game polish element is shown here - https://jamm-labs.github.io/ggcp/add-polish-animate-zapped-sprite/game.js
Going over the code:
First we need to make sure we are adding an an image with more than one frame in it as an animation in our playState.preload area. Be sure to remove any other mentions of a player here. Here is an example.
game.load.spritesheet("player", "https://cdn.glitch.com/21c64338-5965-4de0-a478-2af819796de2%2Fpacmansprites.png",16,16);
We need to add a die animation in the playState.create part of the code after we have added the player to the game. This code does it.
player.animations.add('chomp', [0,1,2], 12,true);
player.animations.add('die', [ 3, 4, 5, 6,7,8,9,10,11,12,13,14,15,16], 12);
player.animations.play('chomp');
Now have a look at the hitHazard function;
var hitHazard = function (player, enemy) {
splatNoise.play();
enemy.kill();
player.body.velocity = 0;
player.animations.play('die');
game.input.keyboard.disabled = true;
game.time.events.add(1200, restart, this);
};
Here a noise is played and then this code gets rid of the enemy the player is stopped by setting velocity to 0 and the keyboard input is turned off so that we can’t move the player around anymore. The animation is now played to show that the player is well and truly zapped.
Then we use a function for a timed event to restart the game. To see that animation we have to delay calling the restart function. In this case we are delaying for 1200 miliseconds which is just over a second.
Lastly as we turned off the keyboard input. We need to turn it back on again in our restart function.
var restart = function () {
game.input.keyboard.disabled = false;
currentLevel = 1;
game.state.start("play", true, false, currentLevel);
};
That’s it. We hope you enjoy adding this element of polish to your game to animated a zapped sprite.