+2 votes

Hello all,

I want to use collision layer and masks to define the behaviour of the collisions of my game. I have already read https://godotengine.org/qa/3020/collision-masks-and-its-propper-uses 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.

in Engine by (73 points)

1 Answer

+12 votes
Best answer

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.

by (21,930 points)
selected by

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

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

definitively true!

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.