Day 24: Giving our enemies the ability to fight back and damage the player

Philip Johnson
3 min readAug 5, 2021

Objective: To fix the orientation of the enemy when engaged with a player and to retaliate and attack the player when in range for combat.

For this next segment we need to attach a child box collider object to the model for the enemy object. Just like we did for the player we will animate this hit box during an attack and call the IDamageable method when we hit the player.

We will also update our animator with transitions from the Idle state to the new attack state.

Now that we have the objects set up to animate, we need to have the player class implement the IDamageable interface in order to use the Damage() method.

We will have to implement the required methods and set our properties from the interface. Luckily visual studio gives us the option to implement it for us.

Now that we can focus on the player, we need to make sure the enemy stays in place when engaged in combat with the player and we need it to face the player in case we jump from one side of the enemy to the other.

we will add this code to the bottom of the Move() method inside of the parent enemy class

When we call the damage method whenever the player attacks an enemy we will run the code shown in the image below

In the child class GiantRat which inherits from the base enemy class we will

When _isHit and the animator bool “InCombat” are set to true we will stop movement and play a hit animation. This will then lead into an attack animation since we set the animator bool “InCombat” to true.

Now that we’ve got the enemy stopping in place and triggering an attack animation, we need to make sure that we are facing then player in case the player jumps from the left and right side during combat. The _direction Vector3 this will return a vector length of where our player is relative to our enemy.

All we have to do now is test our code. The enemy will stop its movement and face the player to attack. The enemy has an animated hit box that activates during the attack animation. If we run away from the enemy, it’s animator bool “InCombat” will be set to false and the enemy will return to patrolling left and right.

The results can be seen in the gif above. Next segment we will focus on playing the proper animations for this spectacle and we will handle enemy and player deaths with animation as well.

--

--