Trying to do something I feel like should be simple but nothing I've tried so far works. I'm trying to prevent this loop from continuing until a property on my enemy is set to true.
My enemy node figures out a path to the player during the walk state. I don't want to iterate to the next enemy until the path has been calculated. My enemy node has a pathComplete node I set to true during the walk state.
This is executed on touch.
for node:AnyObject in self.children {
if node is EnemyNode {
let enemy = node as! EnemyNode
enemy.destination = coordinate
enemy.stateMachine.enterState(WalkingState)
}
}
If I understand what you want to do, then you should use the recursion instead the loop.
First you need to create some enemyNodeArray
that will be contains objects you need.
Then you can make two functions like this:
func actionForObjectWithIndex(index: Int, completion block: (nextIndex: Int) -> Void) {
guard index >= 0 && index < enemyNodeArray.count else {
return
}
// do what you need with object in array like enemyNodeArray[index]...
...
// Then call completion
block(nextIndex: index + 1)
}
func makeActionWithIndex(index: Int) {
actionForObjectWithIndex(index, completion: {(nextIndex: Int) -> Void in
self.makeActionWithIndex(nextIndex)
})
}
and start use it like this:
if !enemyNodeArray.isEmpty {
makeActionWithIndex(0)
}
This algorithm will be take every object in an array, and perform certain actions with them, and it will move to the next item only after it has finished with the previous.