Pregunta

i'm new to sprite kit.. i want to move a sprite randomly on the x axis. for that i need to know how to call another method / the same method with an other random x value when the action is completed. right now the sprite stops at the first random value and do not start moving to the next one.

I tried this:

-(void) move:(CGSize)size {

  if (x1 == x2) {
     x2 = (arc4random() % 320);
     e = 0;
 }

 if (x2 > x1) {
     e = x2 - x1;
 }


 if (x1 > x2) {
     e = x1 -x2;
 }

 t = e/100;

 SKAction *action = [SKAction moveToX:x2 duration:e];
 [_spriteL runAction: [SKAction  repeatAction:action count:1]];

 x1 = x2;

 [self move:size];
  }

thanks

¿Fue útil?

Solución

I had a similar problem. I was trying to move a spaceship along the x axis. I basically generated a random number and ran an action with that. Then within the completion block I recursively called the method again to repeat the process:

- (void)autopilot {
    if (!self.dead) {
        CGVector delta = CGVectorMake((arc4random() % 125), 0);

        NSInteger multiplier = arc4random_uniform(2);
        multiplier = multiplier == 0 ? -1 : 1;
        delta.dx *= multiplier;

        CGPoint position = self.position;
        position.x = position.x <= 0.0 ? 0.0 : position.x;
        position.x = position.x >= self.size.width ? self.size.width : position.x;

        SKAction *move = [SKAction moveBy:delta duration:0.4];
        [self runAction:move completion:^{
            [self autopilot];
            [self shoot];
        }];
    }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top