Animate an 8-directional sprite, part 2: Death Animation

This is a continuation of another blogpost about how to animate a spritesheet in javascript. Read part one here.

This is the animation we’re going to add to the spritesheet

Right now, we have a spritesheet with 8 rows, 1 for each direction of movement. We’re now going to add another row which has a death animation.

The new animation is highlighted at the bottom.

The new animation has 5 frames. The last frame is repeated to fill the empty spaces but we won’t be using those frames.

The first thing to do is add this last row to the constants for referencing it later. We’ll call this last row “DEATH”:

We’ll need a couple new variables as well.

The reviveState isn’t strictly necessary, but for this little project I want to animate a revival sequence. It is an undead skeleton, after all.

We’ll add a new event listener for if there’s a click within a certain radius of the character’s head. Fortunately, there’s already a variable, “hypotenuse”, which I’m using to determine distance from mouse to character. If the character is already dead, clicking will trigger the revive state to become true. If the character is alive, they will become dead and the current keyframe will be set back to 0.

I added a couple of circles just to make it visually clear when you’re close enough to click with an effect, and when you’re close enough to make the character stop moving. This is very much optional, but if you want to draw some indicators like this, just put them within the draw loop but before the character is drawn.

For the code that switches the row of the spritesheet, I added a new case to check the death state as the first case to check so that I don’t trigger any other rows to appear unless the character is alive.

When the character is dead, I need them to stop moving, so I added another “or” statement to the cases for when the character should not be moving.

Finally, here’s where the magic happens! Before if the character was not moving, I just had to make sure the animation didn’t progress in keyframes. Now, if the character is dead but not revived, it triggers a death animation one time only. If you click again to trigger the revive state, the revive animation will run the death animation in reverse, and then set the death state and revive state back to false.

And now we have another way to interact with the character!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store