Objective: Create a hitbox that moves with a character’s animation.
We’ll begin by creating an empty game object under our player’s sprite named Hit Box. This object will have a Box Collider 2D set to Is Trigger and a Rigidbody 2D with Gravity Scale set to 0. We’ll disable the Box Collider 2D so it doesn’t “hit” anything unless the player is attacking.
Now we’ll open the sprite’s Attack animation and enter record mode. We’ll enable the Hit Box’s Box Collider 2D, set its position, and resize the collider to match the sword. We’ll then move on to the next frame of animation, moving and resizing the Hit Box as needed. We’ll have to do this for each frame of animation!
Since the Box Collider 2D is off by default, once the player sprite leaves the Attack animation, the Box Collider 2D will be disabled once again.
Now we’ll add an Attack script to the Hit Box. For now, we’ll just have it tell us what it is hitting.
Uh-oh, the player is hitting itself every time it swings its sword!
Let’s use layers to help us fix this problem. We’ll add a Sword layer and assign the Hit Box to it. We’ll also create a Player layer and assign the rest of the player objects to that layer. Next, we’ll go to Edit → Project Settings and uncheck the box where the Sword and Player layers meet.
Now we can see the player has hit the enemy!