Randomizing SKActions

我与影子孤独终老i 提交于 2019-12-08 06:32:06

问题


I'm trying to move a Sprite over the screen from left to right. The sprite should start at a random y position on the right side offscreen. With a repeatActionForever and an integer with a random Y number i want the sprite to repeat the action starting from different y Positions. Any ideas on how to achieve this besides putting the random int in an update method? Is it anyhow achieveable through actions?

I use this method on the Sprite:

    int randomY = (arc4random()%121;

    SKAction *pos = [SKAction moveTo:CGPointMake((STAGESIZE.width+(self.size.width/2)),randomY) duration:0];
    SKAction *move = [SKAction moveToX:0-self.size.width/2 duration:3];
    SKAction *wait = [SKAction waitForDuration:1 withRange:5];

    SKAction *sequence = [SKAction sequence:@[pos,move,wait]];
    SKAction *repeater = [SKAction repeatActionForever:sequence];
    [self runAction:repeater];

回答1:


There is no way to randomise standard actions once defined and running. But there is a workaround you can use to achieve desired effect using [customActionWithDuration].1

SKAction* randomPositionAction = [SKAction customActionWithDuration:0 actionBlock:^(SKNode *node,CGFloat elapsedTime){
                int randomY = arc4random_uniform(121);
                //Set position instead of running action with duration 0
                [node setPosition:CGPointMake((STAGESIZE.width+(self.size.width/2)),randomY)];
            }];

RandomY is randomised every time action is run and position is set according to that.



来源:https://stackoverflow.com/questions/20652944/randomizing-skactions

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