Search code examples
swiftsprite-kitskspritenodeskphysicsbody

testing if a node is attached to a physicsBody swift


I am getting the node attached to a contact body (SKPhysicsBody), in a function called while detecting a contact between to SKSpriteNode. Sometimes, I get an error because it can not get the node attached to the contact body, so I test if there's a node to avoid that type of error. But a warning tells me it will never return false. I've not had anymore error like this since I test that but I'm not sure if it works well or if it can still happen. Do you have any idea?

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

Solution

  • Thanks for your advices, the error indeed comes from the SKPhysics property (the didBegin function is called several times) but I didn't manage to fix. Although I corrected the way I was checking if a sprite was here, and there are no more warnings or errors so I suppose it works well :

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