Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Know when all SKActions are complete or there aren't any running

I have a number of SKActions running on various nodes. How can I know when they are all completed? I want to ignore touches while animations are running. If I could somehow run actions in parallel on a number of nodes, I could wait for a final action to run, but I don't see any way to coordinate actions across nodes.

I can fake this by running through all the scene's children and checking for hasActions on each child. Seems a little lame, but it does work.

like image 570
ahwulf Avatar asked Nov 26 '13 02:11

ahwulf


1 Answers

The simplest way to do this is using a dispatch group. In Swift 3 this looks like

func moveAllNodes(withCompletionHandler onComplete:(()->())) {
    let group = DispatchGroup()
    for node in nodes {
        let moveAction = SKAction.move(to:target, duration: 0.3)
        group.enter()
        node.run(moveAction, completion: { 
            ...
            group.leave()
        }
    }
    group.notify(queue: .main) {
        onComplete()
    }
}

Before running each action we call group.enter(), adding that action to the group. Then inside each action completion handler we call group.leave(), taking that action out of the group.

The group.notify() block runs after all other blocks have left the dispatch group.

like image 140
bcattle Avatar answered Oct 06 '22 10:10

bcattle