I’m reading Programming Guide Ch12 - Physics and I’m slightly confused how to setup and use CategoryBitmask and CollisionBitmask to filter collisions properly.
Say, I have the following physics bodies:
Body player, dumb, edge, barrier, bonus, tile
player can collide with dumb, edge and bonus
dumb can collide with dumb, edge and barrier
barrier can collide with dumb
bonus can collide with player
tile can collide with nothing
How to setup bitmasks and filter body collisions in such scenario?
Easiest way to think of this is to give each body a power-of-two number
player=1
dumb=2
edge=4
barrier=8
bonus=16
tile=32
This will be their CategoryBitMask
Now to calculate the CollisionBitMask
You want player to collide with dumb, edge and bonus
so the CollisionBitMask is 2 + 4 + 16 = 22.
dumb can collide with dumb edge and barrier
so the CollisionBitMask is 2 + 4 + 8 = 14
barrier collides with dumb
so the collisionBitMask = 2
bonus collides with player
so the collisionBitMask = 1
tile collides with nothing
so the CollisionBitMask = 0
Simple!
The way to works is because the numbers are powers of two, they represent a bit-pattern
00000001 = 1
00000010 = 2
00000100 = 4
00001000 = 8
00010000 = 16
So the collisionBitMask for player (22) is
00010110 = 22
Now, when you logically AND to binary numbers, the result is a 0 in every position except where BOTH numbers have a 1
So, if I take the player bitmask (22) and AND with barrier category (8)
00010110 & 00001000 = 00000000 - which is zero - so they do not collide
AND with the Edge category (4)
00010110 & 00000100 = 00000100 - which is not zero, so they do collide.