Hitbox Attack System in Unity2D

Simon Leen
2 min readSep 30, 2021

--

Objective: Set up Hitbox Attck System

Currently the Player has an animated attack but it has no effect on enemies. To fix this we need to add a HitBox to the Players sword which can then collide with an enemy. We add a new sprite as a child of the Player sprite and rename it HitBox. Next change the Sprite Renderer sprite to the UISprite and set the Order in Layer to match the Player.

Open the Animation window with the Player sprite selected, select the attack animation and lock the animation window to keep it open after the HitBox has been selected. Now move the HitBox into position at the end of the sword and add a Box Collider 2D before editing the collider position, scale and rotation to match the sword in the first frame.

Repeat the keyframe positioning for each frame of the attack moving the HitBox into the new position.

We also need to turn the Hitbox off initially but turn it on at the start of the animation and off at the end again. Once all frames have been accounted for, remove the Sprite Renderer from the HitBox leaving just the Transform and 2D Collider.

Next set the collider to Is Trigger as this is required to hit the enemy but pass through the enemy and not a hard collision. Add a Rigidbody 2D to the HitBox and set the Gravity Scale to 0.

Create a Script inside the Players scripts folder called Attack and add it to the HitBox. In the next post we will set up the Attack script and work with Collision Layers.

--

--

No responses yet