2014-07-13 58 views
0

我有一個圍繞另一個精靈(行星)的精靈(艦隊)軌道運行的方法。問題在於,隨着時間的推移,船隊會進一步移動(非常緩慢,除非讓軌道運行幾分鐘,否則幾乎不會發現)。隨着時間的推移而增加的2D軌道

public void Orbit() 
{ 
    // Planet's position - fleet position 
    Vector2 distanceToDestination = currentLocation.Position - position; 

    // Calculate fleet's rotation (- right angle so fleet rotates clockwise) 
    rotation = MathHelper.WrapAngle((float)Math.Atan2(distanceToDestination.Y, distanceToDestination.X)) - Helpers.RightAngle; 

    // Get the direction that the fleet is facing 
    direction = new Vector2((float)Math.Cos(rotation), (float)Math.Sin(rotation)); 

    // Fleet position, thrust is set to 0.4f 
    position = Vector2.Add(position, direction * thrust); 

    // Fleet rectangle 
    rect = new Rectangle((int)position.X, (int)position.Y, fleetTexture.Width, fleetTexture.Height); 
} 

public static class Helpers 
{ 
    public const float RightAngle = (float)Math.PI/2; 
} 

我將不勝感激,如果社會能指出爲什麼我的車隊是不是保持一致的軌道,這是我想達到的目標!提前謝謝了。

+0

感謝您既爲你出色的答案。 @dbc - 我選擇了你的答案,因爲我使用了你發佈的方法的變體。再次感謝。 – user3256944

回答

2

如果我明白你在做什麼,你試圖模擬軌道物理,使用類似於汽車繞着一個圓圈行駛的模型(也就是說,你不是模擬垂直於當前速度的重力加速度和numerically integrating it)。通過少量d

  • 重新調整,因此「車」仍然是垂直於圓心面臨

    1. 移動垂直於半徑r的圓心:相反,你這樣做。
    2. 重複。

    現在,在每一步之後,你的物體離圓心多遠?那麼,根據畢達哥拉斯定理,它是sqrt(r*r + d*d),它將比r稍大。使用非常大的價值d爲重點:

    enter image description here

    這應該佔你的意思。

    順便提一句,您不需要使用trig函數來構造與distanceToDestination的垂直。用±Z向量簡單地交叉它會容易得多,結果將是(在2d)±(-distanceToDestination.Y, distanceToDestination.X)

    更新:因爲你不是真正模擬軌道物理,爲什麼不解決問題的分析?

    public static Vector2 Orbit(Vector2 center, Vector2 startPos, float speed, float time) 
        { 
         // positive speed means CCW around the center, negative means CW. 
         var radiusVec = (startPos - center); 
         var radius = radiusVec.Length(); 
         var angularVelocity = speed/radius; // Add check for divide by zero 
         Vector2 perpendicularVec = new Vector2(-radiusVec.Y, radiusVec.X); 
         return center + (float)Math.Cos(time * angularVelocity) * radiusVec + (float)Math.Sin(time * angularVelocity) * perpendicularVec; 
        } 
    
  • 1

    這是你所計算的:

    enter image description here

    爲了讓你必須保持矢量lenght軌道的下一個點。

    所以你calculationss應該是:

    // Planet's position - fleet position 
    Vector2 distanceToDestination = currentLocation.Position - position; 
    
    // Calculate fleet's rotation (- right angle so fleet rotates clockwise) 
    rotation = MathHelper.WrapAngle((float)Math.Atan2(distanceToDestination.Y, distanceToDestination.X)); 
    rotation -= Helpers.RightAngle; 
    
    // Get the direction that the fleet is facing 
    direction = new Vector2((float)Math.Cos(rotation), (float)Math.Sin(rotation)); 
    direction *= distanceToDestination.Length; 
    
    position = currentLocation.Position - direction; 
    
    相關問題