They Are Becoming Stronger! Enemies Taking Multiple Hits
In this article, we are going to go over adding a new enemy that can take multiple hits and some animations to bring things to life. The enemy doesn’t have any movement or firing behavior. This will be helpful in adding strength to future enemies.
We are going to declare an int that will store the amount of hits the enemy can take and we will set it to 3.
First, we will jump into the Enemy script and use an OnTriggerEnter2D to detect when the something collides with the Enemy. If the tag is Laser we will destroy the laser after .2 seconds to give the laser hit animation enough time to play before destroying it. Next, we take 1 away from the hit count and play the Enemy Hit animation. Lastly, we need to check if the hit count is 0 and if it is, we will play the Enemy Death animation and Destroy the Enemy after .4 seconds so the animation can play.
I added an animation to the Laser to show impact. Jumping into the Laser script we will add an OnTriggerEnter2D and if the object that collides with the laser is tagged Enemy we will play the animation Laser On Hit animation and set the speed of the laser to 0 so it doesn’t keep moving.
Lets look at the Enemy animator. There are 2 parameters that are triggers. The trigger parameter is a boolean type that reset back after it is played. The On Enemy Hit trigger turns the Enemy red real quick to highlight it has been hit before return back to the normal color. The On Enemy Death trigger plays an explosion animation.
There is a Laser impact animation, so looking looking at the Animator we put an empty state, so the Laser Impact doesn’t play right away when we shoot a laser and can add a transition. The transition is a trigger called On Hit. This is animation will now play with any Game Object tag as Enemy.