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).")
}
}