OpenGL Rotation Around a Point Using GLM

百般思念 提交于 2020-01-04 09:54:12

问题


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);

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);

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?


回答1:


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;

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.



来源:https://stackoverflow.com/questions/26961471/opengl-rotation-around-a-point-using-glm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!