Did you just hit me! — Hitbox attack system in Unity2D

Luke Duckett
4 min readDec 29, 2021

In this article I will go over how to set up an attack system using hitboxes.

I have a player set up already with an attack. What we will do here is set up and animate a collider on our collider when the player attack is triggered.

The first step is to add a new child game object to your player, I called mine “Hit_Box”. This game object will need a collider and a rigid body 2d with no gravity, add these components now.

The box collider 2D to the game object and adjust it to the same size as your weapon by clicking “Edit Collider” and dragging the collider edges in and adjusting the transform, be sure to set the collider to “Is Trigger”.

Note that I've added the hitbox as a child of a game object that has a animator component. This means we don’t need to add an animator controller and script to the hit box game object directly.

The next step is to animate the hit box. Turn the hitbox object off to begin with and then go to your attack animation. On your animation click the record button. The next steps involve moving through the frames of the animation and adjusting the position of the hitbox to match the weapon.

Once you’ve animated the hitbox through the attack you can then turn the game object off.

Now to make sure the collisions will not detect the wrong game object, we are going to set up layers for our player, player attacks, enemy and enemy attacks.

You can then switch your game objects (and child objects) over to their respective layers.

The next step is to edit the layer collision matrix for the player attack layer. Go to “Edit” > “Project Settings” > “Physics2D” > “Layer Collison Matrix” and de-select the player on the player attack layer.

Now we can create a script that will handle the attack when the hitbox hits an object that can take damage. We will use an interface for this to keep our system modular ( I will go over interfaces in another article).

I have created a script for this called IDamageable. In this script we want a property for health and a method to take damage.

Next Implement the interface on an enemy, for this I will use an enemy skeleton I set up earlier. In the Skeleton script we will make sure we inherit from the IDamageable interface.

Now on the hitbox object we can create a script which looks for the IDamageable interface and triggers the Damage function. Note that we have a bool which is set to true on enable and set to false when we find an enemy to hit, this ensures our damage function only gets called once per attack.

Add this script to your hitbox object and test the results.

Now we have successfully implemented a hitbox attack system.

That’s all for now.

--

--

Luke Duckett

🎮 First Nations Unity Dev from Wonnarua country 🏞️ | From Player to Lifelong Learner: Crafting Games, Debugging Code, and Embracing New Technology