Simple Action Loop

128 Views Asked by At

I am trying to repeat a set of actions by running them through a loop. My loop is fine when running something else, but it seems to have trouble running the actions. My code is as follows:

let pulse1 = SKAction.scaleTo(2.0, duration: 1.0)
let pulse2 = SKAction.scaleTo(0.5, duration: 1.0)
var i = 0

override func didMoveToView(view: SKView) {

for var i = 0; i <= 100; i++ { 
self.sun.runAction(pulse1)
self.sun.runAction(pulse2)

}

This will cause the node to pulse1 and pulse2 each once but never again. If I add

println("")

to the loop, it runs whatever text properly, but for some reason doesn't run the actions like it runs the text. Or maybe it does and I don't understand how SKAction works? Either way, the loop is executing properly, I believe. I am not quite sure what's wrong with the SKAction call in the loop.

2

There are 2 best solutions below

3
On

scaleTo simply changes the node's scale. Once pulse1 goes to 2.0 and pulse2 gets to 0.5, runAction runs repeatedly but you never change the scale for either pulse ever again.

That's why you're only seeing it do work the first time.

Instead of using a for loop, try something like this:

override func didMoveToView(view: SKView) {

    if (i % 2 == 0) {
        let pulse = SKAction.scaleTo(2.0, duration: 1.0)
    } else {
        let pulse = SKAction.scaleTo(0.5, duration: 1.0)
    }

    [self.sun runAction:pulse completion:^{

        if( i < 100 )
        {
            didMoveToView(view);
        }

    }];
}
0
On

Maybe you can use

         class func repeatAction(_ action: SKAction,
              count count: Int) -> SKAction

Put as many single actions in a sequence an run repeatAction for x times.