How do I toggle collision masks on and off in script?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Macryc

HI All –

I know I can set a collision layer or mask in code but let’s say I have a kinematicbody node that exists on collision layers 1,2 and 3. In code, I want to move collision layer 3 to 4 whilst leaving 1 and 2 intact, so that the node exists on collision layers 1,2 and 4. How do I do that?

:bust_in_silhouette: Reply From: David Saltares

You’d have to use boolean operations on the mask. For example, you can define the following functions:

func enable_bit(mask: int, index: int) -> int:
    return mask | (1 << index)

func disable_bit(mask: int, index: int) -> int:
    return mask & ~(1 << index)

And then do:

mask = enable_bit(mask, 4)
mask = disable_bit(mask, 3)
:bust_in_silhouette: Reply From: Wakatta

Collision layers are like onions if you want to know it’s contents you have to combine all the layers together. Each layer has a unique bit/value so using a little math simply set the results of all interested layers.

Example

#layer1 value = 1, layer2 value=2 layer4 value8
$kinematicbody.set_collision_layer(11)

#layer1 value = 1, layer2 value=2 layer3 value4
$kinematicbody.set_collision_layer(7)

or use set_collision_layer_bit to enable or disable

#Disable
$kinematicbody.set_collision_layer_bit(3, false)

#Enable
$kinematicbody.set_collision_layer_bit(4, true)

so, as far as I know, kinematicbody.set_collision_layer_bit(11) would set the body’s collision layer to 11 and you could do that for all layers and it’s the same as highlighting the layer numbers in the editor, right? But how do you ‘uncheck’ a collision layer in code?

Macryc | 2021-10-05 12:47

Apologies, had confused a function for another and changed my answer to reflect the corrections.

Wakatta | 2021-10-05 13:36