2011-01-11 141 views
0

我有3個粒子,其中一個是中心粒子。我想通過公式q'=Θq+ p旋轉其他兩個粒子(存儲在粒子列表中),其中q'是旋轉粒子的新位置,θ是方向角,p是中心粒子。其他兩個粒子的初始位置存儲在initialParticlePosition列表中。問題是我認爲我計算的角度是錯誤的,因爲範圍。我應該把範圍作爲[-pi,pi)或類似的東西。在某些部分它計算正確,但有時它是錯誤的。有人可以幫助我使用這個代碼或給我另一種旋轉方法。c#旋轉問題

{ 

     angle = Math.Acos(Vector2.Dot(heading,new Vector2(0,-1))); 

     for (int i = 0; i < 2; i++) 
     { 
      tempX = (double)initialParticlePositions[i].X * Math.Cos(angle) - (double)initialParticlePositions[i].Y * Math.Sin(angle) + centerParticle.position.x; 
      tempY = (double)initialParticlePositions[i].X * Math.Sin(angle) + (double)initialParticlePositions[i].Y * Math.Cos(angle) + centerParticle.position.y; 
      particles[i].position.x = tempX; 
      particles[i].position.y = tempY; 
     } 
} 
+0

用已知的角度值運行代碼並在紙上繪製輸出**。手動驗證輸出。 `cos`和`sin`應該處理[`-pi,pi]`之外的角度(自從我做這種事情已經有一段時間了)。 – ChrisF 2011-01-11 20:06:09

回答

0
angle = Math.Acos(Vector2.Dot(heading,new Vector2(0,-1))); 

當你懷疑,你的點積和反餘弦只會給你一個180度 範圍的角度組合。

取而代之,使用單位矢量上的Atan2來獲取從-pi到pi的全方位角度。

angle = (float)Math.Atan2((double)heading.Y, (double)heading.X); 

如果您的Y軸在向下方向爲正,您可能需要否定Y項。

2

一些方法,可以幫助(角度總是度,而不是弧度):

public static double GetAngle(Vector v) 
    { 
     return Math.Atan2(v.X, -v.Y) * 180.0/Math.PI; 
    } 

    public static Vector SetAngle(Vector v, double angle) 
    { 
     var angleInRads = angle * (Math.PI/180.0); 
     var distance = v.Length; 
     v.X = (Math.Sin(angleInRads) * distance); 
     v.Y = -(Math.Cos(angleInRads) * distance); 
     return v; 
    } 

    static public Point RotatePointAroundCenter(Point point, Point center, double rotationChange) 
    { 
     Vector centerToPoint = point - center; 
     double angle = GetAngle(centerToPoint); 
     Vector centerToNewPoint = SetAngle(centerToPoint, angle + rotationChange); 
     return center + centerToNewPoint; 
    } 

(你應該開始標記的答案,幫助爲答案,點擊左側下方的票對號大綱,例如你可以接受this answer

編輯:優化了方法一下。

+1

+1 ...你可能會提供你正在做什麼的解釋。具體而言,您正在翻譯該點,以便它與原點相關,進行旋轉,然後翻譯回去。 – 2011-01-11 20:27:37

1

被繞粒子位置可以與每個代碼單個線來設置:

假定P1,P2,P3 &被Vector2s和p2 & P3的軌道P1。

p2 = Vector2.Transform(p2 - p1, Matrix.CreateRotationZ(rotationChangeP2)) + p1; 

p3 = Vector2.Transform(p3 - p1, Matrix.CreateRotationZ(rotationChangeP3)) + p1; 

Matrix.Create ...()方法將爲您調用兩個trig函數。

編輯。矩陣& Vector2結構&方法是XNA特定的,但包括在這裏,因爲這是OP標記他的Q。