Search code examples
swiftsprite-kitskphysicsbody

Make Node 'B' and 'C' collide only with Node 'A'


why we can't make didBegin function only called if B or C collides with A but not if B and C collides together? is this possible or we always need to check if something collides with A?

A.physicsBody!.collisionBitMask = 0
A.physicsBody!.contactTestBitMask = 1
A.physicsBody!.categoryBitMask = 1

B.physicsBody!.collisionBitMask = 0
B.physicsBody!.contactTestBitMask = 1
B.physicsBody!.categoryBitMask = 2

C.physicsBody!.collisionBitMask = 0
C.physicsBody!.contactTestBitMask = 1
C.physicsBody!.categoryBitMask = 3

Api says to contactTestBitMask: A mask that defines which categories of bodies cause intersection notifications with this physics body.

we need something like A.contactTestBitMask = 1 & 2


Solution

  • because saying categoryBitMask 3 is the same as saying categoryBitMask 1 AND categortyBitMask 2. See the word bitmask. It is their for a reason. It means you have 32 flags that you can set (or each bit in the provided Int you can set, however you want to look at it).

    Valid unique numbers to bitmasks are anything in the power of 2,

    1
    2
    4
    8 etc

    Which could be represented as

    1 << 1
    1 << 2
    1 << 3
    1 << 4

    or

    0b1
    0b10
    0b100
    0b1000

    However you prefer to write it, the value must be a power of 2.

    So change C to a bitmask value of 4 to make it independent (or make it a value of 2, since B and C share the same collision property, colliding with A)