Swift SpriteKit打开包装

时间:2017-07-11 19:51:50

标签: swift sprite-kit 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)
                }
            }
        }

我的问题是在角度线上。当我在场景中没有zombieGreens时调用该函数时,我遇到了线程1问题。如何在僵尸不存在时更改要考虑的代码?

1 个答案:

答案 0 :(得分:2)

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

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

我认为最简单的解决方案是在不改变大部分代码的情况下使用如果让,就像你对炸弹塔一样。它看起来像这样:

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

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