Search code examples
c++openglglm-math

Opengl GLM lookAt strange behaviour


Currently I am trying to implement shadow mapping for the sun in my game. For this I need to use glm's look at function to render the scene from the sun's perspective. Here is my code:

projection = glm::ortho<float>(-200, 200, -200, 200, -200, 400);
view = glm::lookAt(sun_pos_modelspace, -target_position_modelspace, glm::vec3(0, 1, 0)); // target needs to be negative for correct camera direction
final_matrix = projection * view; 

This works fine since the scene is rendered from the sun's perspective when the game starts. But as I translate target, the view matrix seems to move from its original eye position (which is the sun's position). I do not want the eye to move at all, I just want the camera to sit at the sun's position and just look directly towards the target vector.

Should I be using some other glm function to solve this? Or am I using lookAt incorrectly?


Solution

  • the three parameters to glm::lookAt are eye, center and up. So, you set your eye wherever you want it to be and it should not move by itself. setting it to the sun's position looks correct (but make sure it's in world coordinates)

    what looks a bit fishy is your center parameter. it's supposed to be the point the camera should look at. negating some world position in there doesn't make sense to me :)

    the reason why you have anything on screen despite that negation might be your near plane (second to last parameter in glm::ortho). Usually that's the distance you want objects to be visible in front of your camera. With a negative value, you will see objects that are behind your camera.

    edit: to clarify, it can make sense to have negative near planes in orthografic projections, i just think it's easier to have the sun at some distant location and then let it render everything that is in front of it. that might make this conceptually easier.

    long story short, try not negating the target position and using some positive value for the near plane.