所以我一直在使用 SpriteKit 在 swift 中编写游戏,但我无法理解如何在 swift 中处理变量。我试图在稍后出现的 touchesBegan 函数中再次更新我在 GameScene 类开头声明的变量。但是,我遇到的问题是变量永远不会更新(我知道这一点是因为在 didMoveToView 函数中,变量用于指示节点的旋转,以及何时应该在 touchesBegan 函数中更新它,它永远不会改变节点的旋转)。
在我看来,我可能只是对 Swift 中变量的处理方式存在根本性的误解。我想知道是否有办法更新在类文件中早期声明的变量?
我正在做的事情有意义吗?有谁知道我该如何解决我的情况?我的代码很长,发布所有代码没有意义,所以这里是重要的部分:
这里是我声明“轮换”变量的地方,我稍后会尝试更新和使用它。
class GameScene: SKScene {
let rotation: Int = 188400
这里是 didMoveToView 函数中使用 'rotation' 变量的地方:
let rotate = SKAction.rotateToAngle(CGFloat(-188400), duration: NSTimeInterval(60000))
anchorNode.runAction(rotate)
这里是我尝试更新 touchesBegan 函数中的“旋转”变量的地方:
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
/* Called when a touch begins */
if rotation == 188400 {
println("Setting rotation backwards")
let rotation = -188400
}else{
println("Setting rotation forwards")
let rotation = 188400
}
非常感谢任何帮助!
最佳答案
问题是当你说
let rotation = -188400
您创建一个不同的 rotation
变量并设置它的值。您没有设置实例变量(属性)rotation
。要做到这一点,请省略 let
:
rotation = -188400
我个人喜欢做的是在引用我的实例变量时写self
。所以我会这样写你的代码:
if self.rotation == 188400 {
println("Setting rotation backwards")
self.rotation = -188400
}
等等。 self
的使用不是必需的,但对我来说,它确实澄清了这个变量的来源 - 看起来这样的澄清正是你在这里需要的!
此外,正如@danielbeard 指出的那样,您将能够 更新self.rotation
除非您使用var
声明它>,而不是让
。
关于ios - 快速在函数之间传递变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31572485/