Objective: Create a box collider 2D that is animated with player’s sword to attack enemies.
Create a 2D Object > Sprites > Square named Hit_Box as a child of the Player’s Sprite, as shown below.
The Hit_Box needs the components below, specifically add box collider 2D with is trigger checked and rigidbody 2D with 0 gravity scale. The Sprite renderer maybe used during positioning but removed after all the frames are placed.
Click on animation window and select the Player’s Sprite. Now select the Attack animation from the drop down menu. Lock the animation window using lock icon in top right of animation window. Select the Hit_Box, toggling edit collider, and record. Manually step through the animation frame by frame adjusting enabling the box collider at 0:15 seconds as the swing begins and adjusting the Hit_Box’s position and rotation and the box collider 2D offset and size frame by frame until 0:31 seconds when the box collider 2D is again disabled. Gizmos in upper right are quite helpful visualizing the Hit_Box, as shown below. Stop recording and on Hit_Box disable the box collider 2D by unchecking next to its name. The collider should only be active on the attack swing.
Finally write the Attack script to detect when an sword hits an object. This script uses the OnTriggerEnter2D to detect collisions. Currently it just reports what object is hit.
The Player now has a function Hit_Box, active only when the Player swings the sword. A later article will expand on this Attack script.