Unity has implemented so many features for 2D game creation that it’s natural to want to make one of your own. In this article, we’ll cover an easy wat to create a hitbox attack system.
The first thing we need to do is to add an empty child object to our player sprite. This way we can animate the collider within the attack animation. We can then add a 2D Box Collider as well as a Rigidbody 2D:
Next, we will edit the attack animation and adjust our newly created box collider to follow our weapon. Make sure the track head is placed on the first frame and click the record button and then adjust the collider as necessary:
Once you are happy with the first frame, you have 2 options:
- Adjust the collider for the middle / end frames which allows Unity to tween all frames in between
- Manually edit each frame for precision
The first choice can be considerably quicker and allows you to adjust only the frames that you feel are relevant. The second option is far more accurate but can be rather tedious if your animation has many frames.
Note: If you choose the latter, you will want to change the key frames to “Constant” to maintain accuracy, otherwise Unity will try to smooth out the difference between frames making your hit box look unnatural as seen here:
To correct this, select the frames, right click and select “Both Tangents” then “Constant”
Then your hitbox will track 1:1:
One final step is to enable the collider only during the attack. Otherwise you can have a rogue hitbox in your idle animation like this:
To prevent the collider from appearing in other animations, disable it by default in the hierarchy, then edit your attack animation to enable it on the first frame and disable it on the last frame.
With the hitbox complete, you can now add a simple Attack script to your hitbox with an OnTriggerEnter2D method: