This article will show how to create a simple Hitbox for the Player’s attack. The Hitbox will be activated and deactivated in the attack animation. It will also use the physics layers, so it does not trigger from the Player.
The Hitbox has a Box Collider 2D and Rigidbody 2D components and is a child of the Sprite. As a child, it can be affected by the Animator. The Box Collider 2D is set to be a trigger and is disabled. In the attack animation, the Collider is enabled and disabled.
We set the Hitbox to the PlayerWeapon layer and the Player to the Player layer.
In the Project Settings, under Physics 2D, we set the Player and PlayerWeapon layers to ignore each other by unchecking the crossing checkmark. Now the two layers will never interact.
In the Player script, we add a variable for Hitbox Transform to allow us to move it when the Player flips. Then in Start, we grab the reference by getting the first child of the Sprite Renderer.
To flip the Hitbox, we invert the x-axis value of the local position and then move the Hitbox to that local position.
Next, we will create a simple script and attach it to the Hitbox to report its collisions.
The Attack script prints the name of the GameObject of the Collider that was hit.
The Hitbox is activated when the Player attacks and flips to the direction the Player is facing. The collisions with the Moss Giant are reported in the Console, and the Player is ignored.