我写了一个简单的算法来瞄准 3D 空间。它应该返回从 Start
指向 End
所需的 X、Y 和 Z 旋转。
出于某种原因,无论我如何操作 End
,它总是返回相同的值。
这里出了点问题,但我就是想不通。有人可以告诉我我做错了什么吗?
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);
}
结果应以弧度为单位。 感谢您的建议。
最佳答案
你注意到你在 CalcAngle2D 中使用了两次
ylen
吗?
return (float)Math.Atan2((double)ylen, (double)ylen);
在 Math.Atan2(double y, double x)
中适当使用 xlen
并评估程序的正确性。
关于c# - 为什么这个简单的算法总是返回相同的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5649283/