Sersiego
Sersiego

Reputation: 1

Pause a for Loop for actions - Swift: Sprite Kit

I'm trying to make a deer to jump ramdonly through different defined positions.

func deerJumping () {
   // The different locations are arranged ramdonly
   var places: [CGFloat] = [1124, 852, 1540, 1908, 628, 1736, 392].shuffled()
   //Then the for loop with the actions (jumps) between this positions
   for posc in places {
        //SKAction for the up and down
        //SKAction for the displacement left or right
        //Code for the deer to face the direction of the jump
        //Then run the action:
        deer.run(SKAction.group([jump, move]))
   }
}

The problem is that the loop is not waiting for the actions to finish before to go to the next position in the array.

There's this Pause and Resume a for Loop question that I find. It is about to create NSOperation instances in the loop and add them to an NSOperationQueue but sadly I am a beginner and I don't understand the solution so I have no idea how to apply it to my code.

Any help would be much appreciated!!

Upvotes: 0

Views: 123

Answers (1)

Knight0fDragon
Knight0fDragon

Reputation: 16827

The reason why nothing is waiting is because you run all of your actions at the same time. You want to create an array of actions and run it in sequence

func deerJumping () {
   // The different locations are arranged ramdonly
   var places: [CGFloat] = [1124, 852, 1540, 1908, 628, 1736, 392].shuffled()
   //Then the for loop with the actions (jumps) between this positions
   var actions = [SKAction]()
   for posc in places {
        //SKAction for the up and down
        //SKAction for the displacement left or right
        //Code for the deer to face the direction of the jump
        //Then run the action:
        actions.append(SKAction.sequence([jump, move]))
   }
   var deerRunning = SKAction.sequence(action)
   deer.run(deerRunning)

}

Now I have no idea why you want to pause and resume a for loop, you are going to have to elaborate on that one before I can help you out.

Upvotes: 1

Related Questions