Randomization SKActions

I am trying to move a sprite across the screen from left to right. The sprite should start at an arbitrary position y on the right side of the screen. With repeatActionForever and an integer with a random number Y, I want the sprite to repeat the action, starting at different y positions. Any ideas on how to achieve this other than putting a random int in the update method? How can this be achieved through action?

I use this method in 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
source share
1 answer

It is not possible to randomize standard actions after they are defined and run. But there is a workaround that can be used to achieve the desired effect with [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 , , .

+2

All Articles