c# - 将以度为单位的角度转换为矢量

标签 c# vector xna rotation degrees

我正在做一些游戏编程。 FWIW 我正在使用 XNA,但我怀疑这是否相关。

我想将度数转换为幅度为 1 的方向向量(即 X 和 Y)。

我的原点 (0,0) 在左上角。

所以我想将 0 度转换为 [0, -1]

我认为最好的方法是采用我对北/上的定义并使用矩阵旋转它,但这似乎不起作用。

这是代码...

public class Conversion
{
    public static Vector2 GetDirectionVectorFromDegrees(float Degrees)
    {
        Vector2 North= new Vector2(0, -1);
        float Radians = MathHelper.ToRadians(Degrees);

        var RotationMatrix = Matrix.CreateRotationZ(Radians);
        return Vector2.Transform(North, RotationMatrix);
    }
}

...这是我的单元测试...

[TestFixture]
public class Turning_Tests
{
    [Test]
    public void Degrees0_Tests()
    {
        Vector2 result = Conversion.GetDirectionVectorFromDegrees(0);
        Assert.AreEqual(0, result.X);
        Assert.AreEqual(-1, result.Y);
    }
    [Test]
    public void Degrees90_Tests()
    {
        Vector2 result = Conversion.GetDirectionVectorFromDegrees(90);
        Assert.AreEqual(1, result.X);
        Assert.AreEqual(0, result.Y);
    }
    [Test]
    public void Degrees180_Tests()
    {
        Vector2 result = Conversion.GetDirectionVectorFromDegrees(180);
        Assert.AreEqual(0, result.X);
        Assert.AreEqual(1, result.Y);
    }
    [Test]
    public void Degrees270_Tests()
    {
        Vector2 result = Conversion.GetDirectionVectorFromDegrees(270);
        Assert.AreEqual(-1, result.X);
        Assert.AreEqual(0, result.Y);
    }

}

我是不是完全错了? 我应该使用矩阵吗? 我是不是搞砸了,在错误的地方将度数转换为弧度?

我看到建议可以使用如下代码来完成:

new Vector2((float)Math.Cos(Angle), (float)Math.Sin(Angle));

...或者有时...

new Vector2((float)Math.Sin(Angle), (float)Math.Cos(Angle));

然而这些似乎也不起作用

有人可以让我走上正确的道路......或者更好的是给我一些代码,使提供的 4 个单元测试进入路径?

非常感谢。

最佳答案

只需使用:

new Vector2((float)Math.Cos(radians), (float)Math.Sin(radians))

一定要使用这种方法将度数转换为弧度。

这使用了数学家的惯例,从 [1, 0] 开始并朝着 [0, 1] 的方向前进(即逆时针方向数学家使用的两个轴)。

要改用您的约定(从 [0, -1] 开始并朝 [1, 0] 的方向前进),您需要:

new Vector2((float)Math.Sin(radians), -(float)Math.Cos(radians))

请注意,您从度数到弧度的转换永远不可能精确(它涉及 π 的内容)。您应该在测试中允许一些公差。此外,如果您对 弧度 使用 double 而不是 float,您将在中间计算中获得一些额外的精度。

关于c# - 将以度为单位的角度转换为矢量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18851761/

相关文章:

c++ - 在类里面使用 Map 与 Vector - 速度

c# - XNA 中的四元数旋转

mono - MonoGame可靠吗?

c# - 如何在 Blazor WebAssembly 中配置具有不同配置的多个 HttpClient 实例

c# - Asp.net动态数据修改列大小

c# - 使用带有智能卡证书的signedCms 时出错

c++ - GLSL 变换反馈返回数组与 vector

c# - Java 到 C# - CallableStatement 转换

c++ - 什么时候有人将 std::vector 定义为 thread_local?

c# - XNA Platformer (2D) - 帧率/FPS 波动