Modify the speed of a running SKAction

2019-02-26 06:44发布

问题:

I have this code:

@implementation MyScene {
SKAction *delayAction; 
}
Inside a method:

delayAction = [SKAction waitForDuration:3.0];
[self runAction:[SKAction repeatActionForever: [SKAction sequence:
                                                @[delayAction, [SKAction ...]]]]]
                                                  withKey:@"myKey"];

Then i want to decrease duration overtime. (This method is called on update:) So i tried:

    - (void)updateVelocity
{
    NSLog(@"duration:%f",delayAction.duration);
    delayAction.duration = delayAction.duration - 0.001;
}

And i get:

2014-04-04 11:45:05.781 FlyFish[5409:60b] duration:1.300000
2014-04-04 11:45:05.785 FlyFish[5409:60b] duration:1.299000
2014-04-04 11:45:05.800 FlyFish[5409:60b] duration:1.298000
2014-04-04 11:45:05.816 FlyFish[5409:60b] duration:1.297000

Which seems good, but my [SKAction ...] still continues repeating after 3 seconds.

回答1:

I'd do this a different way. Something like this...

- (void)recursiveActionMethod
{
    if (some end condition is met) {
        return;
        // this allows you to stop the repeating action.
    }

    self.duration -= 0.01;
    // store duration in a property

    SKAction *waitAction = [SKAction waitForDuration:self.duration];
    SKAction *theAction = [SKAction doWhatYouWantHere];
    SKAction *recursiveAcion = [SKAction performSelector:@selector(recursiveActionMethod) onTarget:self];

    SKAction *sequence = [SKAction sequence:@[waitAction, theAction, recursiveAction]];
    [self runAction:sequence];
}

This will perform your action and then come back to this function to be run again with a different wait time and again, and again, ...

You can even stop the sequence by having some end condition that would jump inside the if block and stop the loop.



回答2:

I am a bit late, but you can instead set the action to SKActionTimingEaseOut. Also this is language native and should work slightly faster. (Though you cannot customize the speed changes) This can be done similarly to this:

  1. yourSKAction.timingMode = SKActionTimingEaseOut;