SKAction: How to Animate Random Repeated Actions

五迷三道 提交于 2019-12-10 09:51:28

问题


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?


回答1:


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



回答2:


Yep there's a great Action you can use.

So instead of doing your current runAction do this:

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

You'll also need to change your moveAction moveToX: value to something like arc4random



来源:https://stackoverflow.com/questions/21871508/skaction-how-to-animate-random-repeated-actions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!