Enemy Set Up — Attacking

In this article, we will set up the enemies to attack the Player. The enemies will attack the Player when attacked, and they will be able to damage the Player.

The enemies are set up similar to the Player in the previous article. They have a Hitbox that is activated by the Attack animation. In the Animator for the Skeleton, we transition to the Attack animation whenever the In Combat bool is true and then go back to Idle. The other change we make is that the Skeleton will only walk if In Combat is false.

In the Enemy script, we need to add some variables to control the attack logic.

  1. A bool to know if the Player has hit the Enemy.
  2. The distance from the Player when the Enemy returns to walking.
  3. A reference to the Player to check distance.
  4. The transform for the Hitbox so it can be moved when the Enemy changes direction.

In Start, after getting the Sprite Renderer, we check if it has any children and then gets a reference to the Hitbox transform.

In the Movement method, we check that the In Combat bool parameter is false before ending the method. Next, before moving the Enemy, we check that the is hit equals false and stop moving. If true, we call the Flip method and pass in the Player transform and check the distance from the Player to see if the Enemy should begin moving again.

We change the Flip method to take in a transform and use that in place of the current point. The Hitbox is flipped when the sprite is like the Player.

In the Skeleton script, we disable the Collider and start the Death Routine that will set the Dead bool on the Animator to true, to play the death animation and then destroy the Enemy.

Now the Enemy attacks the Player after it has been hit, flips to face it, and damages it.

Unity Developer, Software Engineer, Game Developer