简体   繁体   English

SpriteKit + Swift中的碰撞检测

[英]Collision Detection in SpriteKit + Swift

I am making a simple Pong game using SpriteKit + Swift. 我正在使用SpriteKit + Swift制作一个简单的Pong游戏。 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: 我在didBeginContact函数中的代码:

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 . firstBody.categoryBitMask设置为firstBody.categoryBitMask以外的其他ballCategory Maybe something like deadBallCategory which is set to 0x0 (or 0, or however you define them, either way, set it to 0). 可能是诸如deadBallCategory类的deadBallCategory ,它设置为0x0(或0,或者无论如何定义它们,将其设置为0)。 Then, your firstBody (the ball) won't keep triggering your didBeginContact function. 然后,您的firstBody (球)将不会继续触发您的didBeginContact函数。 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). 创建要添加到场景中的新球时,请确保将categoryBitMask设置为ballCategory (无论如何看起来都可以)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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