Player Setup — Damage Interface
In this article, we will add the IDamageable interface to the Player from the previous article. This will allow us to damage the Player with a Trigger-able Collider and play a death animation when out of health.
In the Animator for the Player, we make any state transition to the Death animation whenever the Dead trigger is activated.
In the Player script, we will add the IDamageable interface from the previous article and implement it for the Player’s health. Next, we need to add two variables.
- The amount of health the Player will have at the start of the game.
- A bool to know the Player is dead and if the input should be disabled.
- The Health property from the interface.
In the Start method, we set Health to the starting health.
In Update, we check if the Player is dead and end the method to prevent movement.
In the Damage method, we decrement Health, and if it reaches zero, the Player is set to dead, and the Death Routine is started. The Death Routine calls the Death method on the Player Animation, waits for 2 seconds, and then exits Play mode.
In the Player Animation script, we add a method to set the Dead trigger on the Animator to play the Death animation.
The Pain Volume GameObject has a Box Collider 2D set as a trigger, a Rigidbody 2D and Attack script attached. The Attack script is the same as the one on the Player’s Hitbox from a previous article.
The Player takes damage each time the Pain Volume is entered till they die.