使用GLM围绕点进行OpenGL旋转 [英] OpenGL Rotation Around a Point Using GLM

查看:726
本文介绍了使用GLM围绕点进行OpenGL旋转的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读其他文章,内容涉及如何通过将枢轴平移到原点,旋转和向后平移来围绕OpenGL中的点旋转对象.但是,我似乎无法正常工作.我有一个多维数据集,并且正在使用glm :: perspective和glm :: lookAt生成投影和视图矩阵.

I've been reading other posts about how to rotate objects around a point in OpenGL by translating the pivot to the origin, rotating, and the translating back. However, I can't seem to get it working. I have a cube and am using glm::perspective and glm::lookAt to generate the projection and view matrices.

glm::mat4 Projection = glm::perspective(45.0f, 4.0f / 3.0f, 0.1f, 100.0f);
// Camera matrix
glm::mat4 View       = glm::lookAt(
                                   glm::vec3(0,3.5,-5),
                                   glm::vec3(0,0,0), 
                                   glm::vec3(0,1,0)  
                                   );
// Model matrix : an identity matrix (model will be at the origin)
glm::mat4 Model      = glm::mat4(1.0f);

然后,我在while循环内将转换应用于模型矩阵:

Then I apply the transformations on the model matrix like this, inside a while loop:

    if (glfwGetKeyOnce(window, GLFW_KEY_UP))
    {
        Model = translate(Model, vec3(1.0f, 0.0f, 0.0f));
        Model = rotate(Model, 90.0f, vec3(1.0f, 0.0f, 0.0f));
        Model = translate(Model, vec3(-1.0f, 0.0f, 0.0f));
    }
    mat4 MVP = Projection * View * Model;

在我的顶点着色器中,我有这个:

And in my vertex shader, I have this:

gl_Position =  MVP * vec4(vertexPosition_modelspace,1);

但是,这仍然只是将立方体绕其中心旋转.如果我摆脱了对glm :: translate的调用,而是通过调整顶点的x位置进行翻译,则它可以正常工作.但是我认为这不是正确的方法.我在这里想念什么?

However, this still just rotates the cube around its center. If I get rid of the calls to glm::translate, and instead, translate by adjusting the x positions of the vertices, it works properly. But I don't think that's the correct way to do it. What am I missing here?

推荐答案

if (glfwGetKeyOnce(window, GLFW_KEY_UP))
{
    Model = translate(Model, vec3(1.0f, 0.0f, 0.0f));
    Model = rotate(Model, 90.0f, vec3(1.0f, 0.0f, 0.0f));
    Model = translate(Model, vec3(-1.0f, 0.0f, 0.0f));
}
mat4 MVP = Projection * View * Model;

尝试用竖起大拇指的手"形象地显示此代码.拇指是x轴.首先,您举起手,然后走一圈,最后放下手.

try to visualize this code with your "thumbs-up hand". The thumb is the x-Axis. At first you lift your hand, then you walk in a circle, at last you lower your hand.

您最有可能想绕另一个轴旋转.

Most likely you wanted to rotate around another axis.

请记住,还有更多现代方法可以像四元数一样进行旋转.这样可以减轻您的操作负担.

Please bear in Mind there are more modern ways to do rotations like quaternions. This'll spare you loads of operations.

这篇关于使用GLM围绕点进行OpenGL旋转的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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