Search code examples
c++openglopengl-3glm-mathcoordinate-transformation

How do I rotate my camera around my object?


I want to rotate my camera around the scene and an object which is in the center. I've tried doing it this way:

glm::mat4 view;
float radius = 10.0f;
float camX   = sin(SDL_GetTicks()/1000.0f) * radius;
float camZ   = cos(SDL_GetTicks()/1000.0f) * radius;
view = glm::lookAt(glm::vec3(camX, 0.0f, camZ), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f));
glUniformMatrix4fv(glGetUniformLocation(shader, "viewingMatrix"), 1, false, &view[0][0]);

but my object loads up further away on the screen and the object rotates around the scene, not the camera.

That's my vertex shader:

void main()
{
    FragPos = vec3(modelMatrix * vec4(aPos, 1.0));
    Normal = mat3(transpose(inverse(modelMatrix))) * aPos;
    TexCoord = aTexture;

    vec4 transformedPosition = projectionMatrix * viewingMatrix * vec4(FragPos, 1.0f);
    gl_Position = transformedPosition;
}

How do I make it such that the camera is the one rotating around in the scene without the object rotating around?

I'm following this tutorial and I'm trying to work out the what happens in the first animation.

https://learnopengl.com/Getting-started/Camera

modelMatrix

glm::mat4 modelMat(1.0f);
modelMat = glm::translate(modelMat, parentEntity.position);
modelMat = glm::rotate(modelMat, parentEntity.rotation.z, glm::vec3(0.0f, 0.0f, 1.0f));
modelMat = glm::rotate(modelMat, parentEntity.rotation.y, glm::vec3(0.0f, 1.0f, 0.0f));
modelMat = glm::rotate(modelMat, parentEntity.rotation.x, glm::vec3(1.0f, 0.0f, 0.0f));
modelMat = glm::scale(modelMat, parentEntity.scale);
int modelMatrixLoc = glGetUniformLocation(shader, "modelMatrix");
glUniformMatrix4fv(modelMatrixLoc, 1, false, &modelMat[0][0]);

Solution

  • The target of the view (2nd parameter of glm::lookAt) should be the center of the object. The position of the object (and the center of the object) is changed by the model matrix (modelMatrix) in the vertex sahder.

    You have to add the world position of the object to the 1st and 2nd parameter of glm::lookAt. The position of the object is the translation of the model matrix.

    Further the object is to far away from the camera, because the radius is to large.

    To solve your issue, the code has to look somehow like this:

    glm::mat4 view;
    float radius = 2.0f;
    float camX   = sin(SDL_GetTicks()/1000.0f) * radius;
    float camZ   = cos(SDL_GetTicks()/1000.0f) * radius;
    
    view = glm::lookAt(
        glm::vec3(camX, 0.0f, camZ) + parentEntity.position,
        parentEntity.position,
        glm::vec3(0.0f, 1.0f, 0.0f));
    
    glUniformMatrix4fv(
        glGetUniformLocation(shader, "viewingMatrix"), 1, false, glm::value_ptr(view));