我的SKScene类中有3个SKSpriteNode。其中一个是玩家,另一个是金币和不可见的完成物体,例如当玩家触摸它时,游戏就完成了。我的问题是,当玩家与黄金发生冲突时,他的黄金预算应该只增加50黄金。但是,Xcode会检测到多次碰撞,并且金预算增加了很多倍。检测到50-60次碰撞,而不是一次碰撞。我研究了如何解决这个问题。我发现我应该使用Bool,我尝试设置bool,但是并不能解决我的问题。有谁能帮助我如何仅检测一次碰撞?这是我的GameScene类代码:

import SpriteKit
import GameplayKit

class level3: SKScene, SKPhysicsContactDelegate {

    let playerFileName = "player"
    let starFileName = "50Gold"
    let goalFileName = "goal"
    let playerCategory   : UInt32 = 0x1 << 1
    let goalCategory : UInt32 = 0x1 << 2
    let starCategory : UInt32 = 0x1 << 3

    override func didMove(to view: SKView) {
        super.didMove(to: view)
        physicsWorld.contactDelegate = self

        let goal = childNode(withName: goalFileName) as! SKSpriteNode
        let player = childNode(withName: playerFileName) as! SKSpriteNode
        let star = childNode(withName: starFileName) as! SKSpriteNode

        player.physicsBody!.categoryBitMask = playerCategory
        goal.physicsBody!.categoryBitMask = goalCategory

        star.physicsBody?.collisionBitMask = 1
        player.physicsBody?.collisionBitMask = 1
        goal.physicsBody?.collisionBitMask = 1
        goal.physicsBody?.isDynamic = true

        goal.physicsBody!.contactTestBitMask = playerCategory

        player.physicsBody?.isDynamic = true
        star.physicsBody?.isDynamic = true
        player.physicsBody?.contactTestBitMask = starCategory

        star.physicsBody?.categoryBitMask = starCategory

        func didBegin(_ contact: SKPhysicsContact) {

            // 1
            var firstBody: SKPhysicsBody
            var secondBody: SKPhysicsBody
            // 2
            if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
                firstBody = contact.bodyA
                secondBody = contact.bodyB
            } else {
                firstBody = contact.bodyB
                secondBody = contact.bodyA
            }

            if firstBody.categoryBitMask == playerCategory && secondBody.categoryBitMask == goalCategory {

                contact.bodyB.node?.removeFromParent()

            }

            if firstBody.categoryBitMask == playerCategory && secondBody.categoryBitMask == starCategory {

                PlaySceneViewController.instance.gold += 50
                print(PlaySceneViewController.instance.gold)

                contact.bodyB.node?.removeFromParent()

            }

        }
    }
}

最佳答案

是的-这发生了。处理它的方法(在某些情况下,您无法让sprite-kit多次不调用didBegin)是确保您的联系代码可以容纳该代码,并且多次处理合同不会造成问题(例如添加多次得分,删除多个生命,尝试访问已删除的节点或PhysicsBody等)。

有关更多详细信息和可能的解决方案,请参见以下答案:https://stackoverflow.com/a/44384390/1430420

09-25 16:47