第一次接触后立即结束 sprite kit 碰撞

End sprite kit collision immediately after first contact

您好,我正在尝试改进游戏中两个节点之间碰撞的逻辑。我想在玩家接触硬币时更新分数并隐藏节点。它工作正常,但分数在与隐藏节点的整个接触过程中更新了很多次。我想知道是否有办法只 运行 它一次,以便分数更新一次。这是我的代码

    //MARK: SKPhysicsContactDelegate methods

func didBeginContact(contact: SKPhysicsContact) {

    if (contact.bodyA.categoryBitMask == userCategory) && (contact.bodyB.categoryBitMask == objectCategory)  {

        gameOver = 1
        movingObjects.speed = 0
        presentGameOverView()
    }

    if (contact.bodyA.categoryBitMask == userCategory) && (contact.bodyB.categoryBitMask == coinCategory) {
        coinSound()
        contact.bodyB.node?.hidden = true
        score = score + 1
        println(score)
    }
}

您可以在增加分数之前检查节点是否隐藏。

func didBeginContact(contact: SKPhysicsContact) {

    if (contact.bodyA.categoryBitMask == userCategory) && (contact.bodyB.categoryBitMask == objectCategory)  {

        gameOver = 1
        movingObjects.speed = 0
        presentGameOverView()
    }

    if (contact.bodyA.categoryBitMask == userCategory) && (contact.bodyB.categoryBitMask == coinCategory) {
        if !contact.bodyB.node?.hidden // Added line
        {
           coinSound()
           contact.bodyB.node?.hidden = true
           score = score + 1
           println(score)
        }
    }
}

从父项中删除它

func didBeginContact(contact: SKPhysicsContact) {

    if (contact.bodyA.categoryBitMask == userCategory) && (contact.bodyB.categoryBitMask == objectCategory)  {

        gameOver = 1
        movingObjects.speed = 0
        presentGameOverView()
    }

    if (contact.bodyA.categoryBitMask == userCategory) && (contact.bodyB.categoryBitMask == coinCategory) {
         if contact.bodyB.node?.parent != nil {
             coinSound()
             contact.bodyB.node?.removeFromParent()
             score = score + 1
             println(score)
         }
    }
}