pikovayadama
pikovayadama

Reputation: 828

How to set horizontal back and forth movements on a sprite?

I am writing a game where i'm spawning some sprites that move on the same horizontal plane, i.e., their y-coordinate is always the same. I'm not sure physics, but rather only SKActions. Initially I wrote this to spawn the sprite at location Y, and move to a point off the screen in a randomly chosen direction. Now, I'd like this sprite to instead turn around and go backwards until it hits the opposite end of the screen, where I wan it to again turn around, etc.

Initially I have the action set up as such :

SKAction * actionMove = [SKAction moveTo:destination duration:duration];

where destination and duration are basically randomly generated. This obviously moves the sprites in one direction only.

what's an elegant way to I make this an un-ending loop of sprites turning around and repeating their path over and over again?

Upvotes: 0

Views: 1057

Answers (1)

pikovayadama
pikovayadama

Reputation: 828

I figured out how to do this with action sequences. I initially tried setting this up in the
update

method of the scene, and that made everything terribly slow, as expected. So I set up the following sequence of actions (I have the sprites moving back and forth at the same y-coordinate, so they just need to turn around the continue their journey)

CGPoint destination1, destination2;
if (sprite.direction == LeftDirection)
{
    destination1 =CGPointMake(-sprite.size.width/2, sprite.position.y);
    destination2 = CGPointMake(self.frame.size.width + sprite.size.width/2, sprite.position.y);

}else {
    destination1 =CGPointMake(self.frame.size.width + sprite.size.width/2
                             , sprite.position.y);
    destination2 = CGPointMake(-sprite.size.width/2, sprite.position.y);
}

int duration = [sprite getDuration]; //this generates a random duration amount
// Create the actions
SKAction * actionMove1 = [SKAction moveTo:destination1 duration:duration];

//turn the sprite around
SKAction * rotateAction = [SKAction runBlock:^{
    sprite.xScale = sprite.xScale * -1;
    sprite.direction = (sprite.direction == LeftDirection) ? RightDirection : LeftDirection;
}];
//reverse the movement
SKAction * actionMove2 = [SKAction moveTo:destination2 duration:duration];

SKAction * actionMove = [SKAction sequence:@[actionMove1, rotateAction, actionMove2, rotateAction]];

SKAction * repeat = [SKAction repeatActionForever:actionMove];

once this is created, we run the repeat action on the sprite. And voila! continuous movement that changes direction.

Upvotes: 2

Related Questions