Setting Up Layers and Masks in Godot
This is Part 4.1 of the Godot series. Read Previous Parts here.
Why do we need layers?
Layers make sure we don't have situations like the enemy dying on a spike, or taking a coin. While we could write code for it, layers are easy, as they enforce separation for us.
Ensure you setup the layers correctly. Go to Project-> Project Settings -> Layer Names -> 2d Physics, and setup your layers like so:
The way it works is, on the Inspector tab, there are two options--Layer and Mask:
The Layer defines which layer the object is on, while the mask defines which layers it can interact with.
The problem with layers and masks
The biggest problem with layers is that they are non-intuitive, or act in strange ways. For me, I found that 2 objects were on different layers would still interact in strange ways. Spent hours googling, till I found this video:
You dont have to watch the whole thing, I'll give you the tldw:
For things like coins, spikes etc, that the player can interact with but you don't want anything else to interact with, the video recommends not putting them on any layer, but only setting the layer mask. For example, in the spikes layer:
You can see it is not on any layer, but the Mask is set to the player layer. That way, the spike will detect the player, but nothing else. This means in the code we can do:
func _on_spikes_body_entered(_body): die()
Without having to check something like: if body.get_name() == "player"
which I had to do before, as anyone, even enemies could enter the spike zones and kill the player.
If we look at the Player layer:
It is on Layer 1 (player) and can interact with all the other layers (as the mask is on for all). This makes sense, as we want our player to be able to touch everything.
I won't describe all the layers we have– you can look at the code. But hopefully, this was a quick intro to Layers in Godot. We will go back to our normal tutorial next.