旋转Vector3D

时间:2014-01-17 01:09:09

标签: c# vector rotation quaternions

我正在尝试像这样旋转Vector3D:

Vector3D i = new Vector3D(1, 1, 0);
i.Normalize();

Matrix3D m = Matrix3D.Identity;
Quaternion rot = GetShortestRotationBetweenVectors(i, new Vector3D(1, 0, 0));
m.Rotate(rot);

Vector3D j = new Vector3D(0, 1, 0);
Vector3D jRotated = m.Transform(j);
// j should be equal to i

public static Quaternion GetShortestRotationBetweenVectors(Vector3D vector1, Vector3D vector2)
{
vector1.Normalize();
vector2.Normalize();
float angle = (float)Math.Acos(Vector3D.DotProduct(vector1, vector2));
Vector3D axis = Vector3D.CrossProduct(vector2, vector1);

// Check to see if the angle is very small, in which case, the cross product becomes unstable,
// so set the axis to a default.  It doesn't matter much what this axis is, as the rotation angle 
// will be near zero anyway.
if (angle < 0.001f)
{
    axis = new Vector3D(0.0f, 0.0f, 1.0f);
}

if (axis.Length < .001f)
{
    return Quaternion.Identity;
}

axis.Normalize();
Quaternion rot = new Quaternion(axis, angle);

return rot;
}

我得到旋转矩阵从i =(0.77,0.77,0)传递到(1,0,0)=&gt; 45°。所以(0,1,0)旋转45º,结果应为(0.77,0.77,0)。但结果几乎与原始矢量(0,1,0)相同,因此没有进行任何变换。

如何旋转矢量?我有一个向量(x,y,z),这个向量应该旋转到(1,0,0)。对于此操作,假设我们必须旋转30º。那么如何旋转我有30º的所有矢量?

1 个答案:

答案 0 :(得分:2)

最后我发现了问题。

float angle = (float)Math.Acos(Vector3D.DotProduct(vector1, vector2));

以弧度给出角度。

Quaternion rot = new Quaternion(axis, angle);

期望以度为单位的角度

所以解决方案很简单:

float angle = (float)(Math.Acos(Vector3D.DotProduct(vector1, vector2)) * (180 / Math.PI));

这意味着Avateering-XNA(Microsoft官方软件)存在错误。