Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SKAction: How to Animate Random Repeated Actions

Tags:

ios

sprite-kit

I'd like to run a repeating SKAction but with random values on each repeat. I have read this question here that shows one way to do this. However, I want my sprite's movements to be animated, not simply changing its position. One solution I have come up with is to run a sequence of actions, with the final action calling my move method in a recursive fashion:

- (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];
}

Recursively calling this method feels 'icky' to me, but given my limited experience with SpriteKit, seemed like the most obvious way to accomplish this.

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

like image 873
Wayne Hartman Avatar asked Jan 18 '26 23:01

Wayne Hartman


1 Answers

No bells or whistles, but I think this should get you on your way:

Edit: Sorry it should be:

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];
like image 114
T. Benjamin Larsen Avatar answered Jan 20 '26 13:01

T. Benjamin Larsen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!