FLOSS Manuals

 English |  Español |  Français |  Italiano |  Português |  Русский |  Shqip

Learn JavaScript with Phaser

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. So we'll need the following background knowledge;

The code for a minimal example of the Animate Sprite when Zapped game polish element is shown here -  https://add-polish-animate-zapped-sprite.glitch.me/

Going over the code:

Have a look at an updated hitHazard function;

playState.hitHazard = function (player, hazard) {
      game.time.events.add(500, function(){hazard.kill();}, this);          

We have already added a die animation in the create part of the code.

Using an anonymous function for time events: Now in order to see that animation we have to delay calling the kill() function on the sprite we want to get zapped.To do this we can use a game time event. In this case we are delaying for 500 miliseconds which is half a second.

We could create a new named function to call as we did when we started working with timed events in the Adding Animated Cut Scenes chapter. Instead, here we use a different shorter approach called using an anonymous function for one othe time event parameters. The function takes the form --  function()({} -- we put the code we want to run inside the curley brackets.

That's it. We hope you enjoy adding this element of polish to your game to animated a zapped sprite.

There has been error in communication with Booktype server. Not sure right now where is the problem.

You should refresh this page.