Reputation: 99
I am making a simple Pong game using SpriteKit + Swift. Right now I am trying to detect when the ball hits the edge of the screen. When I run my code and the ball hits the edge of the screen, for some reason the score increases twice instead of once. For example the console reads
Player 1 has a score of: 1.
Player 1 has a score of: 2.
when I hit the right side of the screen once.
My code in the didBeginContact function:
func didBeginContact(contact: SKPhysicsContact) {
var firstBody = SKPhysicsBody()
var secondBody = SKPhysicsBody()
if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
firstBody = contact.bodyA
secondBody = contact.bodyB
} else {
firstBody = contact.bodyB
secondBody = contact.bodyA
}
if firstBody.categoryBitMask == ballCategory && secondBody.categoryBitMask == leftSideCategory {
player2Score++
print("Player 2 has a score of: \(player2Score).")
} else if firstBody.categoryBitMask == ballCategory && secondBody.categoryBitMask == rightSideCategory {
player1Score++
print("Player 1 has a score of: \(player1Score).")
}
}
Upvotes: 0
Views: 219
Reputation: 1205
Set the firstBody.categoryBitMask
to something other than ballCategory
. Maybe something like deadBallCategory
which is set to 0x0 (or 0, or however you define them, either way, set it to 0). Then, your firstBody
(the ball) won't keep triggering your didBeginContact
function. When you create a new ball to add to the scene, make sure to set the categoryBitMask
to ballCategory
(which it appears you do anyway).
Upvotes: 1