Day 115 — Creating a Hitbox Attack System in Unity
Hey and welcome!
Just as the title says we’re now going to be looking into implementing the attack system in our game so that our player and enemies can damage one another. First off let’s start by implementing something called a Hitbox for our player’s sword.
In the hierarchy right-click your Sprite object inside your Player object and choose the 2D Object > Sprites > Square option and call this object Hit_Box while making sure that the order in layer is the same as your player. To help visualise things click on the Sprite property for your Sprite Renderer and choose to make this a UISprite. This helps us keep a reference for where our hitbox is while the game is running.
Now add a Box Collider 2D component that’s set as a trigger and a Rigidbody 2D component that has the gravity turned off so that we can use this hitbox to collide with our objects in the game.
Next up is the tedious but fun part about all this and that’s lining up our hitbox with the sword animation. Click on your Sprite object and choose the Attack animation in your animation window. Hit the record button and on the first frame adjust the position and size of your box collider component so that it fits around the sword.
I was adjusting the Z axis to get the desired rotation here. Once you’ve done that you’ll need to move onto the next frame and then readjust the position and size of the box collider if need be and keep doing that until you’ve gone through each frame where the sword is likely to hit an enemy:
Make sure you double check each frame as well since the box collider may shift in size or position between frames. Your end result should be something like the above.
When you test that out during runtime you’ll notice two things, the box collider is always active and it looks a bit off when you swing to the left as we’ve tailored the hitbox specifically for when the player swings to the right. We’re going to leave the latter option for a different article but for the first issue with the box collider all we need to do is turn off the component through the inspector and then re-record our Attack animation enabling the box collider on the first frame.
This makes it so that our box collider becomes active when our attack animation is active!