Hitbox Attack System Unity2D

Ali Emre Onur
3 min readMay 22, 2021

--

I really find this topic exciting. I remember the time how surprised I was to learn how the games decide on if an object actually hit to another object or not.

In the Dungeon Escape game, the Player has an attack system with an attack animation, where he swings a sword.

To create a realistic feeling, we need to make sure that the sword actually hits (collides) with an enemy so that damage will be applied.

But how are we going to know if the sword actually hit the enemy or not? Within the attack animation, we can simply create a collider at the beginning, change its position according to the movement of the sword.

To create this functionality, we need an additional sprite as the child object of the player (it needs to be attached to the object with the Animator component, so if a child object of the player has the animator component, we need to make the hit box child object of that object). Just for visualization purposes, select UISprite from the default list as the Sprite. Also, do not forget to add a collider to the sprite. Now, we can easily manipulate the Hit box with the sword swinging animation.

To match the hit box with the attack animation from the first frame, get to the Animator Tab (lock it) and arrange the position of the hit box collider accordingly (without record on just yet).

Then, hit the record button and align the hit box with the movement of the sword. As we cannot hit an enemy without hitting “Attack”, we need to make sure that box collider of the Hitbox only gets active within the animation (Disable the collider component and enable it on the record button at the first frame).

The attack behaviour will be handled by the hit box game object, so we need to add a script to handle this.

The next thing to handle is managing the trigger collision behaviour.

Collision Layers In Unity

Unity allows us to control the collisions in between layers. To make sure that the sword in the Dungeon Escape game will not be colliding with certain objects (such as the Player), we can use the Layer system of Unity.

I have created a new Layer called “Sword”. With some simple clicking within the Collision matrix, we can tell Unity to detect or not detect collisions in between certain layers.

To reach the Layer Collision Matrix click on Edit — Project Settings — Physics 2D.

To make Unity ignore the collision in between the Player and Sword layers, simply uncheck the corresponding field in the matrix. Of course, do not forget to set the Layers of Player and Sword game objects.

--

--

No responses yet