我寫了一個簡單的算法來做3D空間瞄準。它應該返回指示從Start
到End
所需的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);
}
結果應該是弧度。 謝謝你的建議。
你傳遞相同的參數CalcAngle()? – 2011-04-13 12:37:18
在你的問題或你的代碼中錯字? 'Math.Atan2((double)ylen,(double)ylen)' - 即你在這裏似乎沒有使用xlen。 – 2011-04-13 12:38:39
這是錯誤的! 我是個白癡。認真:) – alex 2011-04-13 12:45:07