gpt4 book ai didi

Swift SpriteKit 展开和包装

转载 作者:行者123 更新时间:2023-11-28 12:20:23 28 4
gpt4 key购买 nike

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

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

关于Swift SpriteKit 展开和包装,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45043397/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com