Objective: Allow the skeleton to attack the player.
Since it is Halloween, the skeleton should to be able to attack the player. Select the Skeleton’s Sprite and add an empty game object naming it Hit_Box. Add the components shown below, box collider 2D, rigidbody 2D and the Attack script. Disable the Box Collider 2D, i.e. uncheck. Add two new layers, the layer Enemy for the Skeleton and Enemy Attack layer for the Hit_Box on Skeleton. In player settings disable interactions between these two new layers under Physics 2D, see previous article.
The Attack script is the same one used previously for our player and is shown below. The details of this script have been previously covered.
The hierarchy should appear as below with Hit_Box a child of the Sprite.
Open the animation window and select the Skeleton’s sprite to create a new clip called Attack. Drag the Skeleton_Attack0 to 30 sprites into the animation window. Space it to play over a minute. Open the Animator window and set up transitions to Attack from Idle and Walk. Use a new bool parameter InCombat to control entry when true with no exit time and transition duration zero. The exit from Attack is when InCombat is false with has exit time checked.
Now click on the Skeleton’s Hit_Box and in the box collider 2D select the edit collider. Begin recording and manually go frame by frame, adjusting the box collider 2D’s enable, rotation, size and offset to match the axe swing, shown below. The box collider 2D is initially off and only enabled on the actual attack portion of the animation.
IDamagable is an interface previously used for the Skeleton, but now add it to Player with “, IDamagable” added immediately after class. It requires a Health variable and Damage() method, both add to the Player script as shown below.
Modify the Enemy abstract class to provide the Skeleton the ability to detect and attack the Player. To do the the enemy needs access to the player as a protected class, so that the derived scripts inherit player.
The virtual void Update() method is shown below. The distToPlayer is calculated and if >2.0 then IsHit and the anim parameter InCombat is set to false, exiting Attack animation. If the distance is less than 2.0f then the skeleton faces the player and sets InCombat to activate the Attack animation. If the skeleton is idle or in combat MoveMonster() is skipped using return.
The Skeleton can now attack the player. Happy Halloween!
This article uses assets from GameDevHQ Filebase.