Day 121 — Implementing Death Animations for the Player and Enemies
Hey and welcome!
It’s time to go over the last touch we need to add to our enemies which is their death animations when they run out of health!
The first part is creating the animations themselves, using our player as a quick example we find the Death sprite sheet for them and slice it up by the player’s dimensions which is 256 x 256. Afterwards we create a new animation on the Sprite object for the player and then we drag and drop our newly created Death sprites into the dope sheet here.
We then adjust the sample rate to our liking which is going to vary between each animation. Now find the animation in your project view and in the inspector set the animation loop time to false. When you’ve finished go ahead and create the animations for your other enemy types in the same way.
Before we get into the code we need to go into each of the animator controllers for our Player and Enemies and create a Death trigger. We then create a transition from Any State to our Death state and make sure that the condition is Death and that there is no exit time. Don’t worry that the Any State already connects to the Hit state in our Skeleton and Moss Giant as you can have multiple transitions coming out of Any State.
Here’s an example of that in our Moss Giant enemy.
Now for the code, head over to your Enemy script and add in the following:
protected bool isDead = false;public virtual void Update()
{
if (anim.GetCurrentAnimatorStateInfo(0).IsName("Idle") && anim.GetBool("InCombat") == false)
{
return;
} if (isDead == false)
{
Movement();
}
}
In here we’re creating a new bool for isDead and then encapsulating our Movement() method inside of an if statement that will run if isDead is false.
You should have a good idea of where I’m going with this so head over to the scripts for each of your enemy types and add in this bit of code to your Damage method when their Health is less than 1:
public void Damage()
{
Health--;
if (Health < 1)
{
isDead = true;
anim.SetTrigger("Death");
}
}
The above is an example of the Damage() method in our Spider script. All that’s happening here is that we’re setting isDead to true which stops our enemies from moving and then triggering their death animations.
With all that together you should have something like the following working for you:
I’d say this is looking pretty good! With all that done, that’s our enemy behaviour sorted for our game now, we’ll look into player damage and death later on but just know that we’ve done everything we’re going to do for our enemies!