Swift SpriteKit 展开和包装

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

我的问题是在 let angle 线上。当我在现场没有 zombieGreens 的情况下调用该函数时,我遇到了线程 1 问题。当僵尸不存在时,如何更改代码以考虑在内?

如果场景中没有 ZombiGreen,错误应该已经发生在第二行:

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

我认为无需更改大部分代码的最简单解决方案是使用 if let,就像您对炸弹塔所做的那样。它看起来像这样:

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

但是当您有更多逻辑要处理时,检查您的代码可能是个好主意。这可能是更好的做事方式,但这应该有效:)