Player Attack System

Hitbox Attack System Unity 2D

Now that we have all the animations and movement script all completed, it is time to target the elephant in the room, the attack sequence.

Attack Sequence Prep:

What we first need to do is create a new sprite component that is a child object of the player sprite. We are going to name this object “hitbox” since this component will control the box collider 2D. Our objective with the hitbox is to trace the collider size to follow the player sword.

Remember to place the newly created sprite “hitbox” as a child object to the Player sprite.

Next you are going to add a Rigidbody 2D to the hitbox object and set the box collider 2D to a Trigger.

Once you have the box collider to follow roughly with the player sword movement it is time to create the “Attack” script that will control the hitbox.

Attack Script:

For now we are going to make sure that the sword itself isn’t going to be affecting the player. To test if the player is going to get hit by the player sword, we can use a On Trigger Enter 2D method with an Debug log that tracks the Colliders name on contact.

Since we know that the player object needs to ignore the sword object, we need to setup individual layers for both the sword and player. Make the Player go under the Player layer and hitbox go under the Sword layer.

Then in the Players Setting > Physics 2D, we need to uncheck the sword layer from the Player layer as shown below. That way the player is going to ignore the sword swings.

To make sure that the other targets are going to get hit, we can apply 2D box colliders for both the skeleton and Moss Giant. Both colliders must also have “ is Trigger” set to true.

As you can see, the Trigger works for the Skeleton enemy.

In the next article we will explain how to animation the damage/hurt effect.

--

--

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