Swift Spritekit I detect a collison but it reads the collision mulitple times

眉间皱痕 提交于 2019-12-19 09:29:13

问题


AppImage I have a wall of 4 rectangles that are different colors, to pass through the wall the color of the ball has to match that of the rectangle on the wall. The ball will pass through the wall, and a new wall will appear. However, when I detect this collision I get multiple collision readings. I have tested this by printing dead or alive, and it prints both or more many times.

func didBegin(_ contact: SKPhysicsContact) {

    if let nodeA = contact.bodyA.node as? SKShapeNode, let nodeB = contact.bodyB.node as? SKShapeNode {
        if nodeA.fillColor != nodeB.fillColor {
            print("DEAD")
        }
        else {
            print("Alive")
        }
    }
}      

please help!!!


回答1:


Yep - this happens. The way to handle it (you can't get sprite-kit to NOT call didBegin multiple times in some circumstances) is to make sure that your contact code accommodates this and that handling the contract multiple times does not cause a problem (such as adding to the score multiple times, removing multiple lives, trying to access a node or physicsBody that has been removed etc).

There is a discussion here: Sprite-Kit registering multiple collisions for single contact

Some things you can do include:

  • If you remove a node that is contacted, check for it being nil before you remove it (for the duplicate contacts)
  • Add the node to a set and then remove all the nodes in the set in didFinishUpdate
  • Add an 'inactive' flag' to the node's userData
  • Make the node a subclass of SKSpriteNode and add an inactive property
  • Etc etc.


来源:https://stackoverflow.com/questions/44379222/swift-spritekit-i-detect-a-collison-but-it-reads-the-collision-mulitple-times

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!