# Cocos-2D asteroids style movement (iOS)

So I have a CCSprite subclass, well call this Spaceship. Spaceship needs to move on a loop, until I say othersise by calling a method. The method should look something like

- (void)moveForeverAtVelocity
{
// method logic
}


The class Spaceship has two relevant iVars, resetPosition and targetPosition, the target is where we are headed, the reset is where we set to when we've hit our target. If they are both off-screen this creates a permanent looping effect.

So for the logic, I have tried several things, such as

CCMoveTo *move = [CCMoveTo actionWithDuration:2 position:ccp(100, 100)];
CCCallBlockN *repeat = [CCCallBlockN
actionWithBlock: ^(CCNode *node) {
[self moveForeverAtVelocity];
}];

[self runAction:[CCSequence actions: move, repeat, nil]];
self.position = self.resetPosition;


recursively calling the moveForeverAtVelocity method.

This is psuedo-code, so its not perfect. I have hard-coded some of the values for the sake of simplicity.

Enough garble: The problem I am having, how can I make a method that loops forever, but can be called and reset at will. I'm running into issues with creating multiple instances of this method. If you can offer any assistance with creating this effect, that would be appreciated.

You can build two different types of motion functions that are called if the positions are off the screen or within the screen.

//within the SpaceShip Class
void Move(){
if(InScreen)
asteroidLikeMotion();
else if(OffScreen)
loopMotion();
}


I am guessing that you already have the mechanism for asteroid like motion. For looping behavior it is much simpler:

x += velocity*cos(direction);
y += velocity*sin(direction);
direction += angularSpeed;