+16 votes

In PhysicsBody and PhysicsBody2D, I see there since a few months a new attribute called Mask (PhysicsBody / Collision / Mask). I noticed that a body collides with another body if they have a layer in common or a mask in common. But then, if there's already a collision layer, what's the purpose of the mask? Alas the documentation is yet incomplete about this subject.

asked May 14, 2016 in Engine by Gokudomatic2 (663 points)

I still haven't seen a good explanation of the difference.

1 Answer

+19 votes
Best answer

Collision mask bit is for choosing what layer should be collided.

Let's assume we set collision layer and mask layer as below.

Player node : collision layer is on 1st bit / mask layer is on 2nd,3rd bit
Enemy node : collision layer is on 2nd bit / mask layer is on 1st bit
Object node : collision layer is on 3rd bit / mask layer is on 1st bit

Player mask(2) == Enemy layer(2)
Player mask(3) == Object layer(3)
so, Player can be collided with Enemy and Object.

but Enemy nodes are not collided each other or Object nodes.
Because Enemy mask(1) != Enemy layer(2) / Enemy mask(1) != Object layer(3)

answered May 14, 2016 by volzhs (9,320 points)
selected May 14, 2016 by Gokudomatic2

Two notes:

  1. If enemy's mask and object's mask are set to 0 (i.e. no layers), they will still collide with the player, because the player's mask still includes their respective layers.
  2. Overall, if the objects are A and B, the check for collision is A.mask & B.layers || B.mask & A.layers, where & is bitwise-and, and || is the or operator. I.e. it takes the layers that correspond to the other object's mask, and checks if any of them is on in both places. It will they proceed to check it the other way around, and if any of the two tests passes, it would report the collision.

thank you very much worked

So basically Collision Layer is to simply organize certain objects onto a layer, and Collision Mask actually tells what objects to collide with?

Great answer! I searched official docs, but no examples for explaining this was found. Thank you for this example, easy to understand now.

It's like the layer can collide with another mask
But a mask can't collide with another mask
The layer collides with both mask and layer
But the mask can't collide with anything by itself

Found a very good explanation at http://kidscancode.org/blog/2018/02/godot3_kinematic2d/

Quoting, so the reader can find it easier:

  • collision_layer describes the layers that the object appears in. By default, all bodies are on layer 1.
  • collision_mask describes what layers the body will scan for collisions. If an object isn’t in one of the mask layers, the body will ignore it. By default, all bodies scan layer 1.

See examples on that page.

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 How to use this Q&A? before posting your first questions.