0
votes

I have been trying to learn scenekit and have finished one book but only collision detection part is not understood, maybe the most important part. There is category mask, collusion mask and physicsbody?.contactTestBitMask.

I want to create a simple game to get this but I got stuck. I am not sure I get the idea.

In game the game, there is a ball and collects pearls, and stays away from rocks and holes. In this case:

Category masks:

  • ball = 0b0001
  • pearls = 0b0010
  • rocks = 0b0100
  • holes = 0b1000

physicsBody?.contactTestBitMask:

  • ball = pearl || rocks // means 0b1110
  • pearls = 1
  • rocks = 1

Collusion masks are 1 because they all collide with each other.

I am not sure I get this collision issue. So before I begin to write code, I wanted to be sure. In SCNPhysicsContactDelegate, function below solves how to learn when they contact with each other:

physicsWorld(_ didBegin contact: _) {

var contactNode:SCNNode!
if contact.nodeA.name == "ball" {
 contactNode = contact.nodeB
 } else {
 contactNode = contact.nodeA
}

if contactNode.physicsBody?.categoryBitMask == 0b0010 {
 // mean pearls
 // raise score etc
}

if contactNode.physicsBody?.categoryBitMask == 0b0100 || 0b1000{
 if contactNode.name == "Rock" { print("You rocked") }
 if contactNode.name == "Hole" { print("You need to climb") }
}

}

I have searched youtube and stack but there is only one explanation. Stack Link Youtube videos are not explaining these. The book examples are copyrighted, so I can't put them on here.

Thank you, Have a nice day.

2

2 Answers

0
votes

You are not using bitwise operators. https://docs.swift.org/swift-book/LanguageGuide/AdvancedOperators.html

change

if contactNode.physicsBody?.categoryBitMask == 0b0100 || 0b1000

to

if contactNode.physicsBody?.categoryBitMask == 0b0100 | 0b1000

The single | and & are the correct operators to use for bitwise operations such as these.

0
votes

There are 3 function to set when you do collision:

mBallBody->setCategoryBitmask(CATEGORY_BALL);
mBallBody->setContactTestBitmask(CATEGORY_WALL_LEFT_RIGHT | CATEGORY_WALL_TOP | CATEGORY_BOX | CATEGORY_LAUNCHER);
mBallBody->setCollisionBitmask(CATEGORY_WALL_LEFT_RIGHT | CATEGORY_WALL_TOP | CATEGORY_BOX | CATEGORY_LAUNCHER);
  1. setCategoryBitmask() --> to set what category this physics belong to!
  2. setContactTestBitmask() --> a mask that defines which categories of bodies cause intersection notifications with this physics body
  3. setCollisionBitmask() --> a mask that defines which categories of phyics bodies can collide with this physics body

so let say ball and wall, ball can collide with wall, so you set contact test bitmask to ball | wall, using | is the bitmask operation.

So you need to set collision category bitmask 1 2 4 8 16 32 and so on.