Collision layer and masks in GDScript

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By VictorSeven
:warning: Old Version Published before Godot 3 was released.

Hello all,

I want to use collision layer and masks to define the behaviour of the collisions of my game. I have already read and I’m aware how the mask-collision system works.

In the editor, I find a menu where I can choose to what collision/masks the object belongs to. As far I can see, an object can be in collision layers 1,2 and 5 and in masks 1 and 3, for example.
However, in code I only have the functions:

set_collision_mask(int mask)  
set_layer_mask(int mask) 

However, here I don’t see clearly how to set this. For example, let’s say I want an object to have collision mask in layers 2 and 5, via code. Using this functions there is no apparent way to eliminate object from layer 1.

So, my question is, how do I actually use these functions to have the object in the correct layers?
I haven’t been able to find the answer in the docs or the QA site.

:bust_in_silhouette: Reply From: kidscancode

Short answer:

To set layers 2 & 5, you would use:


Detailed answer:

To calculate the integer argument for set_collision_mask() you take your desired layer bits, and raise 2 to the power of each layer number.

So, to set layers 2 & 5, you have 2^2 + 2^5, which is 32 + 4 = 36. Note that you can see the values in the UI when you hover over the checkboxes, it will say something like “Bit 4, Val 16”

If you want to check that you’ve set things correctly in code, you can do a test print:

for i in range(20):
    print(i, '\t', get_collision_mask_bit(i))

and you’ll see a list of each bit and its value.

There is also a set_collision_mask_bit that receives 2 parameters, the bit number and the value to set.

quijipixel | 2017-09-06 20:41

Correct, although if you’re setting multiple layers, one set_collision_mask is preferable to multiple set_collision_mask_bit statements.

kidscancode | 2017-09-06 20:47

definitively true!

quijipixel | 2017-09-06 21:00

Not sure, but in godot4, 36 = layer 3 and 6…

Using a bitwise OR works for me though: 2|16.

bendn | 2023-04-15 02:00