代码之家  ›  专栏  ›  技术社区  ›  gamer12

测试节点是否连接到physicsBody swift

  •  0
  • gamer12  · 技术社区  · 7 年前

    我将节点连接到一个contact body(SKPhysicsBody),在检测到SKSpriteNode之间的接触时调用该函数。有时,我会出错,因为它无法将节点连接到接触体,所以我测试是否存在节点以避免此类错误。但是一个警告告诉我它永远不会返回false。自从我测试之后,我再也没有出现过这样的错误,但我不确定它是否工作良好,或者它是否仍然可以发生。你知道吗?

    //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 回复  |  直到 7 年前
        1
  •  0
  •   gamer12    7 年前

    谢谢你的建议,这个错误确实来自SKPhysics属性(didbegen函数被多次调用),但我没有设法修复。

    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
                }
            }
        }
    }