HitBox Attack System in Unity

Here’s how I set up a hitbox for an attack!

So I have an attack animation for the player that I want to set up for attacking enemies as shown below.

The idea is to attach a child game object, with a box collider 2d, to the player sprite and animate it to the motion of the swing.

I like to separate art from the parent of an object. In this case, the Player contains child objects of the Sprite and the SwordArc. The player holds components related to its behavior, and the Sprite game object holds components related to its visual display on the screen.

I created an empty game object under Sprite. I named it HitBox, and it will hold a trigger box collider 2D. The reason why I created the hitbox game object as a child of Sprite is that the Animator in the Sprite game object will have access to its child game objects.

In the Animation panel, I want to track the box collider to the edge of the sword on every frame of the attack animation state.

I made sure the HitBox game object is selected so that I can start recording the position of the box collider.

I readjusted the size of the box collider:

Now for every frame, I move its position to the location of the sword’s tip.

The final result looks like this:

Now that the box collider is animated with the sword, I can attach an attack script to the Hitbox game object. It will detect other colliders it touches. And when it does, I want to call the IDamageable interface from the other game object that was hit and apply damage.

[SerializeField] private int damageAmount = 2;
private bool _onHit = false;
private void OnTriggerEnter2D(Collider2D other)
Debug.Log(“Hit: “ + other.gameObject.name);
var hit = other.GetComponent<IDamageable>();
if (hit != null)
if (!_onHit)
_onHit = true;

The Hitbox collider for the sword will also detect the player’s collider, so I made sure I masked the Hitbox with its own layer called “Sword” to ignore the layer of the player’s collider.

So I checked off the box where Player and Sword meet. It tells Unity to ignore any collision between the two.

The player can now hurt enemies!




Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Gabriel Perez

Gabriel Perez

Hello everyone, My name is Gabriel Perez, I am a Unity Developer and a creator who is always learning and experimenting.