Search code examples
swiftsprite-kitword-wrap

Swift SpriteKit unwrapping and wrapping


func bombTowerTurnShoot() {
let zombieGreen =  self.childNode(withName: "zombie") as! SKSpriteNode
    self.enumerateChildNodes(withName: "bomb tower") {
        node, stop in
            if let bombTower = node as? SKSpriteNode {
            let angle = atan2((zombieGreen.position.x) - bombTower.position.x, (zombieGreen.position.y) - bombTower.position.y)
            let actionTurn = SKAction.rotate(toAngle: -(angle - CGFloat(Double.pi/2)), duration: 0.2)
            bombTower.run(actionTurn)
                }
            }
        }

My issue is on the let angle line. When I call the function when there is no zombieGreens on the scene I get a Thread 1 problem. How can I change the code to take into account when the zombie is not present?


Solution

  • if there is no ZombiGreens in the scene the error should happen already at the second line:

    let zombieGreen =  self.childNode(withName: "zombie") as! SKSpriteNode
    

    I think the simplest solution without changing to much of your code would be to use an if let just as you did for the bomb tower. and it would look something like this:

    func bombTowerTurnShoot() {
                if let zombieGreen =  self.childNode(withName: "zombie") as? SKSpriteNode{
                    self.enumerateChildNodes(withName: "bomb tower") {
                        node, stop in
                        if let bombTower = node as? SKSpriteNode {
                            let angle = atan2((zombieGreen.position.x) - bombTower.position.x, (zombieGreen.position.y) - bombTower.position.y)
                            let actionTurn = SKAction.rotate(toAngle: -(angle - CGFloat(Double.pi/2)), duration: 0.2)
                            bombTower.run(actionTurn)
                        }
                    }
                }
            }  
    

    But it could be a good idea to review your code when you have more logic to handle. it might be a better way to do things but this should work :)