Handmade Network»Forums
25 posts
look at view matrix implementation in GLM lib
Edited by Roman on

I have tried to build lookat view matrix without library but result was wrong. Then I tried glm library lookAt function and it gave me the almost the same matrix as my own function built. The only difference is in translation part. `` glm's translation part in matrix:

Result[3][0] =-dot(s, eye);
Result[3][1] =-dot(u, eye);
Result[3][2] = dot(f, eye);

What? Why it's uses dot product? Isn't it should be a camera position in world? Here is my code.

Camera buildCamera(glm::vec3 cameraOrigin, glm::vec3 lookAt)
    Camera camera = {};
    glm::vec3 up = glm::vec3(0,1,0);
    glm::vec3 forward = glm::normalize(cameraOrigin - lookAt);
    glm::vec3 right = glm::normalize(glm::cross(up, forward));
    up = glm::cross(forward,right);
    f32 c[] = 
        right.x, right.y, right.z,-cameraOrigin.x,
        up.x, up.y, up.z, -cameraOrigin.y,
        forward.x, forward.y, forward.z,-cameraOrigin.z,
        0, 0, 0,1
    camera.cameraMat = glm::transpose(glm::make_mat4(c));
    return camera;


Mārtiņš Možeiko
2570 posts / 2 projects
look at view matrix implementation in GLM lib

LookAt matrix does two steps in this order:

  1. translate to origin
  2. rotate to match your orientation.

If you express these steps as matrix and multiply them in correct order, you will get that dot product for translation.

For your non-dot product case you are doing these steps in opposite order - first rotate, then translate. Which means position will be in wrong place.

This goes into more detail on this (Step 4): https://medium.com/@carmencincotti/lets-look-at-magic-lookat-matrices-c77e53ebdf78