views:

405

answers:

1

I'm developing a line drawing game, similar to Flight Control, Harbor Master, and others in the appstore, using Cocos2D.

For this game, I need a CCSprite to follow a line that the user has drawn. I'm storing a sequence of CGPoint structs in an NSArray, based on the points I get in the touchesBegin and touchesMoved messages. I now have the problem of how to make my sprite follow them.

I have a tick method, that is called at the framerate speed. In that tick method, based on the speed and current position of the sprite, I need to calculate its next position. Is there any standard way to achieve this?

My current approach is calculate the line between the last "reference point" and the next one, and calculate the next point in that line. The problem I have is when the sprite "turns" (moves from one segment of the line to another).

Any hint will be greatly appreciated.

+2  A: 

Why do you code your own tick method? Why don't you just use the built-in CCMoveTo method?

(void) gotoNextWayPoint {
    // You would need to code these functions:
    CGPoint point1 = [self popCurrentWayPoint];
    CGPoint point2 = [self getCurrentWayPoint];

    // Calculate distance from last way point to next way point
    CGFloat dx = point2.x - point1.x;
    CGFloat dy = point2.y - point1.y;
    float distance = sqrt( dx*dx + dy*dy );

    // Calculate angle of segment
    float angle = atan2(dy, dx);

    // Rotate sprite to angle of next segment
    // You could also do this as part of the sequence (or CCSpawn actually) below
    // gradually as it approaches the next way point, but you would need the
    // angle of the line between the next and next next way point
    [mySprite setRotation: angle];

    CCTime segmentDuration = distance/speed;

    // Animate this segment, and afterward, call this function again
    CCAction *myAction = [CCSequence actions: 
          [CCMoveTo actionWithDuration: segmentDuration position: nextWayPoint], 
          [CCCallFunc actionWithTarget: self selector: @selector(gotoNextWayPoint)],
          nil];

    [mySprite runAction: myAction];
}
Jeff B