简体   繁体   中英

Collision Detection in SpriteKit + Swift

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

}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM