0
votes

I created a ball and hope it collides with another sphere. But it's not worked.

enum ColliderType: Int {
   case ball    = 1
   case food    = 2
}

create a ball and a food object

 let ballNode: SCNNode!

 override func viewDidLoad() {

    .......

    let ball = SCNSphere(radius: 1.0)
    ball.materials.first?.diffuse.contents = UIColor.red
    ballNode = SCNNode(geometry: ball)
    ballNode.name = "ball"
    ballNode.position = SCNVecter3(10, 1, 10)
    ballNode.physicsBody = SCNPhysicsBody(type: .kinematic, shape: 
    SCNPhysicsShape(geometry: SCNSphere(radius: 1.0), options: nil))
    ballNode.physicsBody?.categoryBitMask = ColliderType.ball.rawValue
    ballNode.physicsBody?.contactTestBitMask =  ColliderType.food.rawValue
    ballNode.physicsBody?.collisionBitMask = ColliderType.food.rawValue
    scnScene.rootNode.addChildNode(ballNode)                                      


    let food = SCNSphere(radius: 0.5)
    food.materials.first?.diffuse.contents = UIColor.green
    let foodNode = SCNNode(geometry: food)
    foodNode.position = SCNVector3(0, 0.5, 0)
    foodNode.name = "food"
    foodNode.physicsBody = SCNPhysicsBody(type: .static, shape: 
    SCNPhysicsShape(geometry: SCNSphere(radius: 0.5), options: nil))
    foodNode.physicsBody?.categoryBitMask = ColliderType.food.rawValue
    foodNode.physicsBody?.collisionBitMask = ColliderType.ball.rawValue
    foodNode.physicsBody?.contactTestBitMask = ColliderType.ball.rawValue
    scnScene.rootNode.addChildNode(foodNode)

}

Here's the collision code:

func physicsWorld(_ world: SCNPhysicsWorld, didBegin contact: SCNPhysicsContact) {

    var contactNode: SCNNode!

    if contact.nodeA.name == "ball" {
        contactNode = contact.nodeB
    } else {
        contactNode = contact.nodeA
    }

    if contactNode.physicsBody?.categoryBitMask == ColliderType.food.rawValue {
        print("aaaa")
    }

And if I create the food object with scene editor, it's worked. I don't know what's wrong with my code.

1

1 Answers

0
votes

You are using contactTestBitMask for one node and collisionBitMask for the other. SCNPhysicsContact is governed by contactTestBitMask.

Also, I do not see whether physicsBody is assigned to the ball node.