CCSprite遵循一系列CGPoints

时间:2010-04-08 22:01:17

标签: iphone cocos2d-iphone

我正在使用Cocos2D开发一个线图绘制游戏,类似于Flight Control,Harbor Master和appstore中的其他人。

对于这个游戏,我需要一个CCSprite来跟随用户绘制的一条线。我根据CGPointNSArray消息中的点,在touchesBegin中存储了一系列touchesMoved结构。我现在遇到了如何使我的精灵跟随它们的问题。

我有一个tick方法,以帧速率调用。在该tick方法中,基于精灵的速度和当前位置,我需要计算它的下一个位置。有没有标准的方法来实现这个目标?

我当前的方法是计算最后一个“参考点”和下一个参考点之间的线,并计算该线中的下一个点。我遇到的问题是精灵“转动”(从一段线移动到另一段)。

任何提示都将受到高度赞赏。

1 个答案:

答案 0 :(得分:6)

为什么要编写自己的tick方法?为什么不使用内置的CCMoveTo方法?

(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];
}