使用glm将四元数转换为矩阵

15

我正在尝试将glm中的四元数转换为mat4。

我的代码如下:

#include <iostream>
#include<glm/glm.hpp>
#include<glm/gtc/quaternion.hpp>
#include<glm/common.hpp>
using namespace std;


int main()
{
    glm::mat4 MyMatrix=glm::mat4();
    glm::quat myQuat;

    myQuat=glm::quat(0.707107,0.707107,0.00,0.000);
    glm::mat4 RotationMatrix = quaternion::toMat4(myQuat);

    for(int i=0;i<4;++i)
    {
        for(int j=0;j<4;++j)
        {
            cout<<RotationMatrix[i][j]<<" ";
        }
        cout<<"\n";
    }
    return 0;
}
当我运行程序时,它显示错误“error:‘quaternion’未声明”。 有人能帮我解决这个问题吗?

3
需要将quaternion::toMat4替换为glm::quaternion::toMat4吗? - NathanOliver
2个回答

22

添加以下内容:

#include <glm/gtx/quaternion.hpp>

修复 toMat4 的命名空间:

glm::mat4 RotationMatrix = glm::toMat4(myQuat);

glm::toMat4() 函数位于 gtx/quaternion.hpp 文件中,你可以在 这里查看,该文件仅有 glm 命名空间。


另外,需要注意的是,在 C++14 中不允许使用嵌套命名空间(例如 glm::quaternion::toMat4)


3
在C++14中不允许嵌套命名空间定义,但在问题中没有定义这样的命名空间。无论如何,在C++17中是允许的。 - scry
在评论中提到过,但事后我应该在那里回复。 - meepzh

13

除了meepzh的答案外,也可以这样做:

glm::mat4 RotationMatrix = glm::mat4_cast(myQuat);

不需要 #include <glm/gtx/quaternion.hpp>


在 Fedora-32 桌面 (Linux) 上,确实需要上述的 include。 - user3882729

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接