我在做一些游戏编程。 FWIW我正在使用XNA,但我怀疑这是否相关。
我想将度数转换为幅度为1的方向向量(即X和Y)。
我的起源(0,0)位于左上角。
所以我想要0度转换为[0,-1]
我认为最好的方法是采用我对North / Up的定义并使用矩阵旋转它,但这似乎不起作用。
以下是代码......
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个提供的单元测试路径?
非常感谢提前。
答案 0 :(得分:15)
只需使用:
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
代替radians
,则中间计算中会有一些额外的精度。