2

我一直在尝试使用正确的模拟摇杆创建延迟旋转效果。下面的代码根据右侧模拟摇杆的输入获取角度,并使对象稳定地靠近。由于 atan2 是 -pi 到 pi 的范围,因此不断变化的旋转总是倾向于通过 0 弧度而不是 pi。有没有办法使角度朝相反的方向移动?

    private void Angle()
    {
        //Angle to go to
        RotationReference = -(float)(Math.Atan2(YR, XR));

        //Adds on top of rotation to steadily bring it closer
        //to the direction the analog stick is facing
        Rotation += (RotationReference - Rotation) * Seconds *15;
        Console.WriteLine(RotationReference);
    }

编辑:

我尝试使用 InBetween 建议的方法,导致 2pi 到 0 之间的转换出现问题。这让我尝试了别的东西。我不知道为什么它不起作用。

    private void Angle()
    {
        //Angle to go to
        RotationReference = -(float)(CorrectedAtan2(YR, XR));

        //Adds on top of rotation to steadily bring it closer
        //to the direction the analog stick is facing
        if (Math.Abs(RotationReference - Rotation) > Math.PI)
            Rotation += ((float)(RotationReference + Math.PI * 2) - Rotation) * Seconds * 15;
        else Rotation += (RotationReference - Rotation) * Seconds *15;
        Console.WriteLine(RotationReference);
    }

    public static double CorrectedAtan2(double y, double x)
    {
        var angle = Math.Atan2(y, x);
        return angle < 0 ? angle + 2 * Math.PI: angle;
    }

这背后的想法是,如果您需要行进超过 180 度,您将使行进角度大于 360 度。这应该消除反转方向的需要。

4

2 回答 2

0

只需校正角度以适合[0, 2·pi]​​范围:

public static double CorrectedAtan2(double y, double x)
{
    var angle = Math.Atan2(y, x);
    return angle < 0 ? angle + 2 * Math.PI : angle;
}
于 2016-06-10T13:06:28.147 回答
0

经过一些实验,我设法使它工作。感谢 InBetween 提供的 CorrectedAtan2 方法。for 循环用于遍历您需要添加 pi 以避免不和谐的过渡的所有实例。

    private float Angle(float y, float x)
    {
        //Angle to go to
        RotationReference = -(float)(CorrectedAtan2(y, x));

        for (int i = 0; i < 60; i++)
        {
            if (Math.Abs(RotationReference - Rotation) > Math.PI)
                RotationReference = -(float)(CorrectedAtan2(y, x) +
                    (Math.PI * 2 * i));
        }
        //Adds on top of rotation to steadily bring it closer
        //to the direction the analog stick is facing
        return Rotation += (RotationReference - Rotation) * Seconds * 15;
    }

    public static double CorrectedAtan2(double y, double x)
    {
        var angle = Math.Atan2(y, x);
        return angle < 0 ? angle + 2 * Math.PI: angle;
    }
于 2016-06-11T00:58:15.213 回答