Setting Up a Hitbox Attack System in Unity2D (2): Working with Collision Layers
In the previous article, we all but set up the hitbox attack system for use in our player and enemies. The problem we’ll face at this stage is that the Attack script and hit box on our player’s sword will damage the player as well as enemies (assuming they’re both implementing the IDamageable interface). One of the cleaner, simpler workarounds for this is to ensure our player, enemies, player sword, and enemy attacks are on unique collision layers. Let’s walk through this process:
1. Select the parent object of your Player and click the Layer dropdown. Select “Add Layer” and type in the name(s) of the layers you want to create. Since we’re here, let’s just add in the four we know we’re going to need right now: Sword, Player, Enemy, and Enemy_Attack.
2. Apply the “Player” layer to your root/parent Player object and apply it to any child objects too. Do the same using the “Enemy” layer for any enemies you’d like to set up. Now select the hit box we set up for the player and apply the “Sword” layer specifically. Finally for this step, select any enemy hit boxes and apply the “Enemy_Attack” layer.
3. Now let’s adjust what’s referred to as the “Layer Collision Matrix” in Unity. Head over to Edit > Project Settings > Physics 2D to take a look at this. This handy little graphic shows us which layers can collide or interact with which other layers. By default, all layers will interact/collide with each other, but if we untick (in this case) the Player > Sword interaction as well as the Enemy > Enemy_Attack interaction we can prevent player’s attack from registering with the player and the enemy’s attacks from registering with enemies.
If you’ve done all of this, we should now be ready to go! As long as we continue to apply the correct layers to our GameObjects, we can have the enemy and player hit boxes make use of the same Attack script and Damage method! 😄
[I’ll cover how we can set up the “Hit” animations shown on the enemy in gif in a subsequent article 😉]