Most Efficient Way to Check Collisions in didBeginContact

孤街浪徒 提交于 2019-12-08 14:10:47

问题


What's the best way to check for collision using SpriteKit's didBeginContact method. I'm currently checking by class and doing something like this:

if let thisMine = nodeA as? Mine {
    if nodeB is Player {
       thisMine.explode()
   }
}
else if let thisMine = nodeB as? Mine {
    if nodeA is Player {
       thisMine.explode()
   }
}

I'm doing this a bunch of times in the didBeginContact method because I have lots of different objects that can interact with each other. Is it more efficient to be checking by the bit masks? Also, is there a way to cut down on needing to basically duplicate all the code by checking nodeA and nodeB as the same class?


回答1:


Use category bitMasks:

    func didBeginContact(contact: SKPhysicsContact) {
        let contactMask = contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask

        switch contactMask {

        case categoryBitMask.player | categoryBitMask.thisMine:
           print("Collision between player and thisMine")
           let mineNode = contact.bodyA.categoryBitMask == categoryBitMask.thisMine ? contact.bodyA.node! : contact.bodyB.node!
           mineNode.explode()

        default :
           //Some other contact has occurred
           print("Some other contact")
    }  
}


来源:https://stackoverflow.com/questions/37996254/most-efficient-way-to-check-collisions-in-didbegincontact

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