Search code examples
c++opengl-esshaderglulookat

How to use LookAt matrix in vertex shader


Let's say I have the following vertex shader code below:

attribute vec4 vPos;
uniform mat4 MVP;
uniform mat4 LookAt;

void main{
     gl_Position = MVP * vPos;
}

How do I use the LookAt matrix in this shader to position the eye of the camera? I have tried LookAt * MVP * vPos but that didn't seem to work as my triangle just disappeared off screen!


Solution

  • I would suggest move the LookAt outside the shader to prevent un-necessary calculation per vertex. The shader still do

    gl_Position = MVP * vPos;
    

    and you manipulate MVP in the application with glm. For example:

    projection = glm::perspective(fov, aspect, 0.1f, 10000.0f);
    view = glm::lookAt(eye, center, up);
    model = matrix of the model, with all the dynamic transforms.
    
    MVP = projection * view * model;