Developingdeveloper Developingdeveloper - 6 months ago 10
Swift Question

Accesing local defined variable in other functions - Swift

I am making a game kind of like Space Invaders.
I have a function that creates invaders at a random

position.x
.

Inside my
addInvader()
, I have defined the attacker as a
SKSpriteNode(imageNamed: "someImage")
.

This have to be defined inside the function, since there are added a new
attacker
every second.

My problem is inside another function:

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


Since the
attacker
constant is local, the
update(currentTime: NSTimeInterval)
function can`t access it.

How can I access the
attacker.position
inside the update-function?

Answer

I created a global array called attackers. Then I simply added the each attacker to the array.

With an algorythm, I made sure the updatefunction was keeping track of the right attacker.