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

Fred Brooks’ silver bullet

Top 10 Flutter Articles of the Past Month (Oct 2018)

Object Oriented Programming 101 — Classes and Objects

Full development lifecycle for PySpark data flows using Databricks on AWS and GitLab

Automated Testing

Trouble-free File Server Access and Search for Macs

What exactly is an Application Service Provider (ASP)?

Why Can’t We Agree on One Sensible Date Format?

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

2D Mobile: Loot System

Creating Elevator in Unity — Part 3: Moving Elevator.

Did you just hit me! — Hitbox attack system in Unity2D

Building A Stealth Game — Creating Waypoints For Your AI Guards