在其他函数中访问本地定义的变量 - Swift

Accesing local defined variable in other functions - Swift

我正在制作一款类似于 Space Invaders 的游戏。 我有一个随机创建入侵者的功能position.x

在我的 addInvader() 中,我将攻击者定义为 SKSpriteNode(imageNamed: "someImage")

这必须在函数内部定义,因为每秒都会添加一个新的 attacker

我的问题出在另一个函数中:

override func update(currentTime: NSTimeInterval) {
    if attacker.position.y < CGFloat(size.height/5*2)
        attacker.texture = SKTexture(imageNamed: "someOtherImage")
    }
}

由于 attacker 常量是局部的,update(currentTime: NSTimeInterval) 函数无法访问它。

如何访问更新函数中的 attacker.position

There is no way you can access a variable that was defined privately in a method.

但是你能做的就是这个..

在您的 addInvader() 方法中,在这个

下面
var attacker = SKSpriteNode(imageNamed: "someImage")

您需要添加以下代码

attacker.name = "attacker" 

您可以将 attacker.name 设置为您想要的任何值,即 String

设置这将使我们能够在 SKScene 中找到节点并使用它

现在,一旦我们有了这个集合,我们就可以继续使用 update(currentTime: NSTimeInterval) 方法了。在 update(currentTime: NSTimeInterval) 中,只需在其他任何内容之前添加这行代码

let attacker =  self.childNodeWithName("attacker") as! SKSpriteNode

它的作用是遍历 SKScene 中的所有子项并查找名称为 attacker 或您设置的任何名称的子项。如果 attacker 节点不是 SKScene 的子节点,而是另一个变量的子节点,例如 attackerParent 那么您可以做的是

let attcker = attackerParent.childNodeWithName("attacker") as! SKSpriteNode

所以现在你的更新函数看起来像这样

let attacker = self.childNodeWithName("attacker") as! SKSpriteNode

if attacker.position.y < CGFloat(size.height/5*2) {

    attacker.texture = SKTexture(imageNamed: "someOtherImage")

}

还有一个小技巧,如果你想改变一个SKSpriteNode的纹理,像这样

var texture = SKTexture(imageNamed : "someOtherImage")
attacker.texture = texture

我创建了一个名为 attackers 的全局数组。 然后我简单地将每个攻击者添加到数组中。

通过算法,我确保 update 函数跟踪正确的攻击者。