我有一个名为bomb tower
的局部变量。代码如下:
if checkMark.contains(touchLocation) {
let bombTowerLevel1 = SKSpriteNode(imageNamed: "bomb tower trial 2")
bombTowerLevel1.name = "bomb tower" //change later maybe
bombTowerLevel1.position = bombTowerGhost.position
bombTowerLevel1.zPosition = 1 //change later for health
bombTowerLevel1.setScale(frame.size.height/2500)
self.addChild(bombTowerLevel1)
}
我稍后使用此处的name
访问它:
func turretShoot() {
let bombTower = self.childNode(withName: "bomb tower") as! SKSpriteNode
bombTower.zRotation = mainturret.zRotation
}
让我明确一下,场景中可能会有多个炸弹塔,因此我没有将bomb tower
作为全局变量。当前代码的问题在于,当我放置一个以上的炸弹塔时,该功能中的动作仅由放置的第一个炸弹塔执行。关于如何访问局部变量并让每一个炸弹塔转向的任何想法?
答案 0 :(得分:6)
使用SKNode的enumerateChildNodesWithName
来设置所有节点的旋转名称:
func turretShoot() {
self.enumerateChildNodes(withName: "bomb tower") {
node, stop in
if let bombTower = node as? SKSpriteNode {
bombTower.zRotation = mainturret.zRotation
}
}
}