Search code examples
openglcamerarotationprojection

opengl rotated object not centered


I am learning modern opengl(3.3), and atm I am creating my own mvp matrices. I just have some weird problem, when I try to rotate the world, my camera does not seem to rotate around the center. Here is an image of a triangle centered at the origin, while rotating. http://postimg.org/image/5l4k4cjqz/

These are my matrices:

glm::mat4 model = glm::mat4(1.0);
glm::mat4 view = glm::lookAt( glm::vec3(0.0, 0.0, 5.0),
                              glm::vec3(0.0, 0.0, 0.0), 
                              glm::vec3(0.0, 1.0, 0.0) );
glm::mat4 projection = glm::perspective(45.0f, 1024.0f / 768.0f, 0.1f, 100.0f);
glm::mat4 xRotation = glm::rotate( glm::mat4(1.0f), this->xAngle, glm::vec3(1.0, 0.0, 0.0) );
glm::mat4 yRotation = glm::rotate( glm::mat4(1.0f), this->yAngle, glm::vec3(0.0, 1.0, 0.0) );
glm::mat4 zRotation = glm::rotate( glm::mat4(1.0f), this->zAngle, glm::vec3(0.0, 0.0, 1.0) );
glm::mat4 mvp = projection * view * model * xRotation * yRotation * zRotation;

When I remove the projection matrix from the mvp matrix, it will rotate around the center.

PS: Is there a better way to do the rotation, can I put it in the view matrix?


Solution

  • If the camera is located at c, and you want to rotate it around the pivot point p, you have to first translate the camera by d = p - c, then rotate, then translate it back by -d. I'm not familiar with glm, so here's just pseudo code.

    viewMatrix = translationMatrix(-d) * rotationMatrix * translationMatrix(d)