2010-04-08 26 views
2

我正在使用Cocos2D開發一個類似於Flight Control,Harbor Master和其他應用程序的繪圖遊戲。CCSprite遵循CGPoints序列

對於這個遊戲,我需要一個CCSprite來跟隨用戶繪製的一條線。根據我在touchesBegintouchesMoved消息中獲得的幾點,我將一個CGPoint結構的序列存儲在NSArray中。我現在有如何讓我的精靈跟着他們的問題。

我有一個滴答法,這是在幀速率調用。在該tick方法中,基於精靈的速度和當前位置,我需要計算它的下一個位置。有沒有任何標準的方法來實現這一目標?

我目前的做法是計算最後一個「參考點」和下一個參考點之間的線,並計算該線的下一個點。我遇到的問題是精靈「轉身」(從一個線段移動到另一個線段)。

任何提示將不勝感激。

回答

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