NFC.cool
NFC.cool

Reputation: 3303

How to set up multiple collision in SceneKit Scene Editor

I'm playing around with the new SceneKit Editor in XCode 7. I managed to get collision with two objects. I was wondering how can I specify collision with more than one category. Let's say the player collides with the ground and the enemy. How can I achieve that with just those two input fields?

XCode7 Scenekit Editor Collision

Upvotes: 2

Views: 461

Answers (1)

lock
lock

Reputation: 2897

The key is to make sure your categories are all powers of 2 (2,4,8,16,etc) so you can make full use of the bitmask.

To check if two objects collide SceneKit will do something similar to the willCollide func shown below. A bitwise AND (&) operator is used to check if any of the bits in the Ints match in both the category and collidesWith. If any bits match, the objects should collide.

func willCollide(category:Int, collidesWith:Int) -> Bool {
    return category & collidesWith != 0
}

Using powers of 2 means that each category has a unique bit position in the Int.

let cat1:Int = 2    // 00010
let cat2:Int = 4    // 00100
let cat3:Int = 8    // 01000
let cat4:Int = 16   // 10000

willCollide(cat1, collidesWith: cat1)  // true
willCollide(cat1, collidesWith: cat2)  // false

You can use a bitwise OR (|) operator to combine multiple Ints, which in this case allows a category to contact multiple other categories.

let cat1and2 = cat1 | cat2  //  00110 or 6 in decimal
willCollide(cat1, collidesWith: cat1and2)  // true
willCollide(cat2, collidesWith: cat1and2)  // true
willCollide(cat3, collidesWith: cat1and2)  // false

For your example something like the following would work;

  • Player
    • category = 2
    • collision mask = 12
      • 4 | 8 = 0010 | 0100 = 0110 = 12
  • Enemy
    • category = 4
    • collision mask = 2
  • Ground
    • category = 8
    • collision mask = 2

It's important to set the collision mask for both the enemy and ground, as sometimes the enemy will collide with the player. This is different to the player colliding with the enemy. Note: I've left out the bit where the enemy would also contact the ground and vice-versa.

Upvotes: 2

Related Questions