四元数到旋转矩阵,使用特征库的值不正确

时间:2016-04-08 13:46:20

标签: c++ opengl matrix rotation quaternions

我正在尝试使用关于Y轴的四元数将对象旋转45度。 指定四元数后我试图获得旋转矩阵。但我看到的值不正确

Eigen::Quaterniond q;
q.x() = 0;
q.y() = 1;
q.z() = 0;
q.w() = PI/8;    // Half of the rotation angle must be specified, even IDK why

Eigen::Matrix3d R = q.normalized().toRotationMatrix();
std::cout << "R=" << std::endl << R << std::endl;

输出:

R=
-0.732    -0   -0.680
     0     1       -0
 0.680     0   -0.732


由于沿Y轴的OpenGL旋转矩阵应为:

enter image description here

因此我的预期输出应为:

R=
 0.707     0    0.707
     0     1        0
-0.707     0    0.707

不仅价值偏低一小部分值上的错误符号导致一些意外的旋转。由于负号,我的立方体正在进行180度转弯加上指定的角度。这一整天都让我不知所措。有人可以告诉我我做错了吗?

1 个答案:

答案 0 :(得分:11)

初始化四元数的方式不正确。如果直接初始化四元数的坐标,则应考虑definition

enter image description here

或者,Eigen中的Quaternion类提供axis-angle representation的构造函数。

此代码:

#include <Eigen/Geometry>
#include <iostream>

void outputAsMatrix(const Eigen::Quaterniond& q)
{
    std::cout << "R=" << std::endl << q.normalized().toRotationMatrix() << std::endl;
}

void main()
{
    auto angle = M_PI / 4;
    auto sinA = std::sin(angle / 2);
    auto cosA = std::cos(angle / 2);

    Eigen::Quaterniond q;
    q.x() = 0 * sinA;
    q.y() = 1 * sinA;
    q.z() = 0 * sinA;
    q.w() = cosA;    

    outputAsMatrix(q);
    outputAsMatrix(Eigen::Quaterniond{Eigen::AngleAxisd{angle, Eigen::Vector3d{0, 1, 0}}});
}

输出您的期望:

R=
 0.707107         0  0.707107
        0         1         0
-0.707107         0  0.707107
R=
 0.707107         0  0.707107
        0         1         0
-0.707107         0  0.707107
相关问题