Search code examples
iosobjective-cios7sprite-kit

Continually repeat an action


I want my action to repeat every 2 seconds. Here is my current code:

    SKSpriteNode *lightnut = [SKSpriteNode spriteNodeWithImageNamed:@"lightnut.png"];
    BOOL heads = arc4random_uniform(100) < 50;
    lightnut.position = (heads)? CGPointMake(257,510) : CGPointMake(50,510);
    [self addChild: lightnut];

    SKAction *moveNodeUp = [SKAction moveByX:0.0 y:-600.0 duration:2.0];
    [lightnut runAction: moveNodeUp];

How would I repeat the action that is being said in the code above over and over again? I want the sprite to start moving, wait 2 seconds, and then start another one. Is it possible to send another sprite before the original sprite has finished moving to the next spot?

Thank you!


Solution

  • I suggest you use an SKAction to generate the sprites since actions pause/resume appropriately when you pause/resume the scene or view. Here's an example of how to do that:

    // Declare SKAction that waits 2 seconds
    SKAction *wait = [SKAction waitForDuration:2.0];    
    
    // Declare SKAction block to generate the sprites
    SKAction *createSpriteBlock = [SKAction runBlock:^{
        SKSpriteNode *lightnut = [SKSpriteNode spriteNodeWithImageNamed:@"lightnut.png"];
        BOOL heads = arc4random_uniform(100) < 50;
        lightnut.position = (heads)? CGPointMake(257,510) : CGPointMake(50,510);
        [self addChild: lightnut];
    
        SKAction *moveNodeUp = [SKAction moveByX:0.0 y:-600.0 duration:2.0];
        [lightnut runAction: moveNodeUp];
    }];
    
    // Combine the actions
    SKAction *waitThenRunBlock = [SKAction sequence:@[wait,createSpriteBlock]];
    
    // Lather, rinse, repeat
    [self runAction:[SKAction repeatActionForever:waitThenRunBlock]];