2D Character Setup in Unity — Attack Hitbox

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.




Unity Developer, Software Engineer, Game Developer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

A 360 Degree View Of Software Engineering — part 1

Reasons behind Big Industries Automate Reporting with Tableau

Containerisation done right: reduce infrastructure TCO and product time to market. Part 1

Earn a QuickSwap-themed REVV Racing car NFT by adding liquidity to REVV/QUICK pool on QuickSwap

8 Common Arguments Against Vaccines.aws

Server-Less AWS — Making Developers’ Life Easy In 2022

Introduction to Git Workflow

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
Kyle W. Powers

Kyle W. Powers

Unity Developer, Software Engineer, Game Developer

More from Medium

Creating a Physics Based Character Controller from Scratch in Unity

Creating Enemy Explosions

Making a RTS game #39: Boosting our game scene (Unity/C#)

Journal 146 — Unity Project Development, 2.5D Shooter