Day 116 — Working With Collision Layers in Unity

Connor Fullarton
3 min readJul 9, 2021

--

Hey and welcome!

In the last one we implemented a hitbox for our sword attack and in this one we’re going to go over how to create a sword layer and register collision with other objects when the player attacks.

To start things off click on your Player object and then click on the layer drop down in the top right of the inspector and choose the Add Layer option. Once in here add in a Sword and Player layer and exit back out.

Once you’ve done that go ahead and set the layer on your Player object to Player and it will give you a warning letting you know that the child objects will have this set as their layer as well, go ahead and Ok that. Next up go into your Hit_Box object again and this time set the layer for this to Sword.

Now we’re going to do something pretty cool next, as it stands currently if we make our hitbox collideable it’s going to come across an issue where it will collide with our player object which is something we don’t want and it brings new meaning to the phrase “Stop hitting yourself”.

Open up your Project Settings by going to Edit > Project Settings and navigate to the Physics 2D section. Click on Layer Collision Matrix option and in here you’re going to see all your layers in a table with the option to check and uncheck certain ones.

What this is doing is determining which layer can interact with the other as shown by them intersecting. Go ahead and find the Sword/Player checkbox and Uncheck, it could also be Player/Sword depending on the order of your layers.

Now our sword hit_box isn’t going to collide with the Player when we swing it!

Since we’ve got a bit of time let’s do some set up for the attack system, first create a new script called Attack and enter in this code:

private void OnTriggerEnter2D(Collider2D other)
{
Debug.Log("Hit " + other.name);
}

Once you’ve done that you can attach the script to your Hit_Box object. Now click on one of your enemies that you have in the scene and add a Box Collider 2D component to it that’s set as a trigger and map it around your enemy.

Now you’re ready to run your game and take a swipe at the enemy! If done right you’ll see this output in your console “Hit Skeleton” with Skeleton being the name of your enemy. Without our intervention with the layers this would also output “Hit Player” but it’s a good thing we took care of that already.

--

--

Connor Fullarton
Connor Fullarton

Written by Connor Fullarton

Hey and welcome! My name is Connor and my goal here is to put out a daily post for a full year about my game development journey.

No responses yet