2011-04-13 34 views
0


我寫了一個簡單的算法來做3D空間瞄準。它應該返回指示從StartEnd所需的X,Y和Z旋轉。 出於某種原因,它始終返回相同的值,無論我如何操縱End
這裏有些事情真的不對,但我無法弄清楚。有人能告訴我我做錯了什麼嗎?爲什麼這個簡單的algorthim總是返回相同的值?

public static void CalcAngle(Vector3 start, Vector3 end, out float xAngle, 
out float yAngle, out float zAngle, bool Radians) 
    { 
     Vector2 xzPlaneStart = new Vector2(start.X, start.Z); 
     Vector2 xzPlaneEnd = new Vector2(end.X, end.Z); 
     Vector2 xyPlaneStart = new Vector2(start.X, start.Y); 
     Vector2 xyPlaneEnd = new Vector2(end.X, end.Y); 
     Vector2 zyPlaneStart = new Vector2(start.Z, start.Y); 
     Vector2 zyPlaneEnd = new Vector2(end.Z, end.Y); 

     float xrot, yrot, zrot; 
     xrot = yrot = zrot = float.NaN; 
     xrot = CalcAngle2D(zyPlaneStart, zyPlaneEnd); //Always 0.78539 
     yrot = CalcAngle2D(xzPlaneStart, xzPlaneEnd); //Always -2.3561945 
     zrot = CalcAngle2D(xyPlaneStart, xyPlaneEnd); //Always 0.78539 
     if (Radians) 
     { 
      xAngle = xrot; 
      yAngle = yrot; 
      zAngle = zrot; 
     } 
     else 
     { 
      xAngle = MathHelper.ToDegrees(xrot); 
      yAngle = MathHelper.ToDegrees(yrot); 
      zAngle = MathHelper.ToDegrees(zrot); 
     } 
    } 
    public static float CalcAngle2D(Vector2 v, Vector2 end) 
    { 
     float xlen = end.X - v.X; 
     float ylen = end.Y - v.Y; 
     return (float)Math.Atan2((double)ylen, (double)ylen); 
    } 

結果應該是弧度。 謝謝你的建議。

+0

你傳遞相同的參數CalcAngle()? – 2011-04-13 12:37:18

+2

在你的問題或你的代碼中錯字? 'Math.Atan2((double)ylen,(double)ylen)' - 即你在這裏似乎沒有使用xlen。 – 2011-04-13 12:38:39

+1

這是錯誤的! 我是個白癡。認真:) – alex 2011-04-13 12:45:07

回答

4

你注意到你在CalcAngle2D?

return (float)Math.Atan2((double)ylen, (double)ylen); 

使用ylen兩次使用xlen在適當情況下Math.Atan2(double y, double x)和評估程序的正確性。

+0

你明白了,謝謝。 – alex 2011-04-13 12:46:27

2

你不應該回xlenCalcAngle2D

return (float)Math.Atan2((double)**xlen**, (double)ylen); 
相關問題