SKAction: how to animate random repeating actions

I would like to run a repeating one SKAction, but with random values ​​for each repeat. I read this question here , which shows one way to do this. However, I want my sprite animations to be animated, rather than just changing their position. One of the solutions I came up with is to execute a sequence of actions, with the last action calling my move method recursively:

- (void)moveTheBomber {
    __weak typeof(self) weakSelf = self;

    float randomX = //  determine new "randomX" position

    SKAction *moveAction = [SKAction moveToX:randomX duration:0.25f];
    SKAction *waitAction = [SKAction waitForDuration:0.15 withRange:0.4];
    SKAction *completionAction = [SKAction customActionWithDuration:0 actionBlock:^(SKNode *node, CGFloat elapsedTime) {
        [weakSelf moveTheBomber];
    }];

    SKAction *sequence = [SKAction sequence:@[moveAction, waitAction, completionAction]];

    [self.bomber runAction:sequence];
}

A recursive call to this method feels icky to me, but given my limited experience with SpriteKit, it seemed like the most obvious way to accomplish this.

How can I endlessly animate the random movement of a sprite on the screen?

+3
2

, , :

: , :

SKAction *randomXMovement = [SKAction runBlock:^(void){
    NSInteger xMovement = arc4random() % 20;
    NSInteger leftOrRight = arc4random() % 2;
    if (leftOrRight == 1) {
        xMovement *= -1;
    }
    SKAction *moveX = [SKAction moveByX:xMovement y:0 duration:1.0];
    [aSprite runAction:moveX];
}];

SKAction *wait = [SKAction waitForDuration:1.0];
SKAction *sequence = [SKAction sequence:@[randomXMovement, wait]];
SKAction *repeat = [SKAction repeatActionForever:sequence];
[aSprite runAction: repeat];
+6

, , .

, runAction :

[self.bomber runAction:[SKAction repeatActionForever:sequence]];

moveAction moveToX: - arc4random

+2

All Articles