Search code examples
iosswiftscenekit

How to set collision bit mask to `all` in SceneKit in Swift


I need to set a SCNNode's collisionBitMask to the default value, which is all bit set.

It turns out to be pretty tricky, and the following is my research so far:

collisionBitMask is an Int type (not UInt)!

The default value is all (a bit mask whose every bit is enabled), specifying that the body will collide with bodies of all other categories.

Then clicking into the link, we have:

static var all: SCNPhysicsCollisionCategory { get }

From SCNPhysicsCollisionCategory's doc, we know the rawValue is a UInt.

i can't direct cast UInt to Int since I will lose precision:

toyUI.physicsBody?.collisionBitMask = Int(SCNPhysicsCollisionCategory.all.rawValue)

I got this error:

Swift/Integers.swift:3687: Fatal error: Not enough bits to represent the passed value


Solution

  • Try to set it like so:

    toyUI.physicsBody?.collisionBitMask = Int.max
    

    SCNPhysicsCollisionCategory.all.rawValue (as UInt) enables all 64 bits. Int.max also sets all bits except the sign bit to 1, which is sufficient to represent the "all categories".