When the ball collides with the cup, the score should increase by 1. However it currently increases by 1, 3 or sometimes 4 which means the collision is being detected multiple times.
I think I must be checking for collisions incorrectly:
let ballCategory : UInt32 = 0x1 << 0
let cupCategory : UInt32 = 0x1 << 1
And in my didMoveToView
:
//Set physicsBody of scene to a physics body that borders the screen
self.physicsBody = SKPhysicsBody(edgeLoopFromRect: self.frame)
physicsWorld.contactDelegate = self
//Ball
ballSprite.physicsBody = SKPhysicsBody(rectangleOfSize: ballSprite.size)
ballSprite.physicsBody!.categoryBitMask = ballCategory
ballSprite.physicsBody!.contactTestBitMask = cupCategory
//Cup
cupSprite.physicsBody = SKPhysicsBody(edgeLoopFromRect: cupSprite.size)
cupSprite.physicsBody!.categoryBitMask = cupCategory
cupSprite.physicsBody!.contactTestBitMask = ballCategory
In my didBeginContact
:
var firstBody: SKPhysicsBody
var secondBody: SKPhysicsBody
//Assign the two physics bodies so that the one with the lower category is always stored in firstBody
if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
firstBody = contact.bodyA
secondBody = contact.bodyB
}
else {
firstBody = contact.bodyB
secondBody = contact.bodyA
}
//contact between ball and cup
if firstBody.categoryBitMask == ballCategory && secondBody.categoryBitMask == cupCategory {
score++
println("point scored")
moveBall() //Move ball back to start position
}
This works in the sense that it is detecting the collision, however it is happening multiple times whereas it should only happen once.