c# - 旋转矢量3D

标签 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) => 45°。所以 (0, 1, 0) 旋转 45°,结果应该是 (0.77, 0.77, 0)。但结果与原始向量(0,1,0)几乎相同,因此没有进行任何变换。

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

最佳答案

终于找到问题所在了。

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(微软官方软件)存在错误。

关于c# - 旋转矢量3D,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21176086/

相关文章:

java - 我有一个数组,我想将其剥离并转换为另一个数组

ios - 在 UIButton 中,setImage 和 setBackgroudnImage content id 不同,它旋转了 90 度

IOS:旋转 uiimageview

html - 倾斜的 Div - 仅右侧

c# - 看不到其他文本框

c# - 从类型访问 JsonObject 标题

c# - IDisposable 对象作为方法的 ref 参数

c++ - 存储未初始化的 STL vector ?

类错误的 C++ vector

c++ - 多次 push_back vector 的快速方法