简体   繁体   中英

OpenGL orthographic camera zooming not working properly

I've implemented a little 2d camera for my scene. The problem is that if I try to zoom the camera some how moves left and downwards instead of zooming in (each objects moves upwards and right). I'm not sure what I've done wrong.

Camera.cpp:

void Camera2D::zoom(float zoomFactor)
{
    scale = glm::scale(scale, glm::vec3(zoomFactor, zoomFactor, 0));
    updateMatrix();
}

void Camera2D::updateMatrix()
{
    translate = glm::translate(glm::mat4(1.f) , glm::vec3(-400, -300, 0));//zoom from center of 
screen
    view = translate * scale;
    translate = glm::translate(glm::mat4(1.f), glm::vec3(0, 0, 0));
    view = translate * scale;
}

I'm sending the mvp matrix to the shader like this: projection * view * model. The zoom factor is just 1.001.

I assume that you use an orthographic projection, where the bottom left is (0, 0) and the top right is (800, 300).
So the center of the view is (400, 300).

If you want to zoom the view, around the center of the orthographic projection, then you've to:

  • translate the center to the origin. This means translate by (-400, -300).
  • zoom (scale)
  • translate the origin back to the center. This is a translation by (400, 300).
void Camera2D::updateMatrix()
{
    glm::vec3 center(400.0f, 300.0f, 0.0f);
    glm::mat4 view = glm::translate(glm::mat4(1.0f), center) * 
                     scale *
                     glm::translate(glm::mat4(1.0f), -center);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM