将glm :: lookat矩阵转换为四元数并返回 [英] Converting glm::lookat matrix to quaternion and back

查看:497
本文介绍了将glm :: lookat矩阵转换为四元数并返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用glm创建相机类,并且我在使用lookat函数时遇到了一些问题.我正在使用四元数来表示旋转,但是我想使用glm的预先编写的lookat函数来避免重复代码.这是我现在的lookat函数:

void Camera::LookAt(float x, float y, float z) {
    glm::mat4 lookMat = glm::lookAt(position, glm::vec3(x, y, z), glm::vec3(0, 1, 0));
    rotation = glm::toQuat(lookMat);
}

但是,当我打电话给LookAt(0.0f,0.0f,0.0f)时,我的相机并没有旋转到该点.在lookat调用之后调用glm::eulerangles(rotation)时,我得到一个带有以下值的vec3:(180.0f,0.0f,180.0f). position是(0.0f,0.0f,-10.0f),所以我完全不应该旋转以查看0,0,0.这是构建视图矩阵的函数:

glm::mat4 Camera::GetView() {
    view = glm::toMat4(rotation) * glm::translate(glm::mat4(), position);
    return view;
}

为什么我没有得到正确的四元数,我该如何修复我的代码?

解决方案

解决方案:

您必须通过共轭来反转四元数的旋转:

using namespace glm;

quat orientation = conjugate(toQuat(lookAt(vecA, vecB, up)));


说明:

lookAt函数替代了 gluLookAt ,用于构造视图矩阵.. >

视图矩阵用于旋转查看器周围的世界,因此是摄影机变换的逆函数.

通过取逆的逆,可以得到实际的变换.

I am using glm to create a camera class, and I am running into some problems with a lookat function. I am using a quaternion to represent rotation, but I want to use glm's prewritten lookat function to avoid duplicating code. This is my lookat function right now:

void Camera::LookAt(float x, float y, float z) {
    glm::mat4 lookMat = glm::lookAt(position, glm::vec3(x, y, z), glm::vec3(0, 1, 0));
    rotation = glm::toQuat(lookMat);
}

However when I call LookAt(0.0f,0.0f,0.0f), my camera is not rotated to that point. When I call glm::eulerangles(rotation) after the lookat call, I get a vec3 with the following values: (180.0f, 0.0f, 180.0f). position is (0.0f,0.0f,-10.0f), so I should not have any rotation at all to look at 0,0,0. This is the function which builds the view matrix:

glm::mat4 Camera::GetView() {
    view = glm::toMat4(rotation) * glm::translate(glm::mat4(), position);
    return view;
}

Why am I not getting the correct quaternion, and how can I fix my code?

解决方案

Solution:

You have to invert the rotation of the quaternion by conjugating it:

using namespace glm;

quat orientation = conjugate(toQuat(lookAt(vecA, vecB, up)));


Explanation:

The lookAt function is a replacement for gluLookAt, which is used to construct a view matrix.

The view matrix is used to rotate the world around the viewer, and is therefore the inverse of the cameras transform.

By taking the inverse of the inverse, you can get the actual transform.

这篇关于将glm :: lookat矩阵转换为四元数并返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆