In the previous article, we created a hitbox to attack. However, once you test the function, you will notice that the sword would hit Player itself.
To avoid this situation, we need to use layer.
Create layer to sword and Player
First we need to add a new layer. Select Player and find drop down menu of Layer in Inspector on the top right, then select “Add Layer”.
Inside Layer window, find an empty column and create a new name. In here, we can create a “Sword” and a “Player”.
Then we can assign the Layer to Player and Sword. When assign layer to Player, it would ask if you want to change layer to all children. It is fine to select agree, later we can select sword layer individually to Sword.
Once finished setting layers, we can make the sword to avoid hitting Player.
Layer Collision Matrix
Open Project Setting from the drop down menu. Then select Physics2D, find out Layer Collision Matrix at the bottom. Uncheck between Player and Sword.
Once you uncheck it. These 2 layers would no longer collide with each other.
Now you can freely to swing your sword!