c# - 为什么这个简单的算法总是返回相同的值?

标签 c# algorithm xna


我写了一个简单的算法来瞄准 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/

相关文章:

c# - 简单的正则表达式问题

c# - 尽管具有相同代码的字段工作正常(在 C# MVC、ASP.Net Core 中),但 DateTime 验证不起作用

c# - 方法 'System.Linq.Queryable.SelectMany System.Linq.IQueryable 的类型参数

c++ - 使用 Boost::Geometry Polygon boolean/intersections 与线段属性

c# - 如何在 2D 游戏中计算屏幕到世界的位置

audio - 可以知道XNA SoundEffects中当前是否正在播放声音实例吗?

c# - Azure 上的 Google Analytics API

algorithm - 事件参与者的个性化时间表

algorithm - 跳转到下一个最近的元素

c# - 为技能使用添加冷却时间