我正在做一些游戏编程。 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/