测试节点是否附加到physicsBody swift

时间:2017-10-26 14:56:27

标签: swift sprite-kit skspritenode skphysicsbody

我正在将一个节点连接到一个联系人体(SKPhysicsBody),这个函数在检测SKSpriteNode之间的联系时被调用。有时,我收到一个错误,因为它无法将节点连接到联系人体,所以我测试是否有一个节点来避免这种类型的错误。但警告告诉我它永远不会返回虚假。因为我测试了,所以我没有这样的错误,但是我不确定它是否运作良好或是否仍然可以发生。你有什么想法吗?

//The actual code
func didBegin(_ contact: SKPhysicsContact) {
    if (contact.bodyA.categoryBitMask == enemyCategory) && (contact.bodyB.categoryBitMask == shootCategory){ //test if it is the contact with I want to catch
        let shootNode = contact.bodyB.node, shootNode != nil { // I test if there's a node attached to the enemyShootNode but it's supposed never to return false
            let enemyNode = contact.bodyA.node, enemyNode != nil { // I test if there's a node attached to the shootNode but it's supposed never to return false
                let enemySKNode = enemyNode as? SKSpriteNode
                let shootSKNode = shootNode as? SKSpriteNode
                // code
            }
        }
    }
}

   // The code with error
func didBegin(_ contact: SKPhysicsContact) {
    if (contact.bodyA.categoryBitMask == enemyCategory) && (contact.bodyB.categoryBitMask == shootCategory){
        let shootNode = contact.bodyB.node!
        let enemyNode = contact.bodyA.node! // The error occurs here : "fatal error: unexpectedly found nil while unwrapping an Optional value"
        let enemySKNode = enemyNode as? SKSpriteNode
        let shootSKNode = shootNode as? SKSpriteNode
     }
}

1 个答案:

答案 0 :(得分:0)

感谢您的建议,错误确实来自SKPhysics属性(didBegin函数被多次调用),但我没有设法修复。 虽然我纠正了我检查精灵是否在这里的方式,并且没有更多的警告或错误所以我认为它运作良好:

func didBegin(_ contact: SKPhysicsContact) {
    if (contact.bodyA.categoryBitMask == enemyCategory) && (contact.bodyB.categoryBitMask == shootCategory) || (contact.bodyA.categoryBitMask == shootCategory) && (contact.bodyB.categoryBitMask == enemyCategory){
        if var shootNode = contact.bodyB.node{
            if var enemyNode = contact.bodyA.node{
                // If the enemyNode and the shootNode don't respectively correspond to 
                if contact.bodyA.categoryBitMask == shootCategory {
                    shootNode = contact.bodyA.node!
                    enemyNode = contact.bodyB.node!
                }
                let enemySKNode = enemyNode as? SKSpriteNode
                let shootSKNode = shootNode as? SKSpriteNode
            }
        }
    }
}