Search code examples
openglglulookat

problems with gluLookAt


I am trying to test gluLookAt using this code. But I can see only a black screen. What is wrong with this code ? Is there any basic concept about glulookAt (or opengl camera) that I need to understand.

glViewport(0,0,640,480);
glEnable(GL_DEPTH_TEST);
glClearColor(0,0,0,1);

glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluLookAt(0,0,5,0,0,0,0,0,1);

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

glBegin(GL_POLYGON);
glColor3f(1, 0, 0);
glVertex2d(0.25, 0.25);
glVertex2d(-0.25, 0.25);
glVertex2d(-0.25, -0.25);
glVertex2d(0.25, -0.25);
glEnd();

Solution

  • One issue is the up vector of gluLookAt is in the same direction as the look direction.

    All you need to do is set +Y up and it should work...

    gluLookAt(0, 0, 0.5, //position is +0.5 along Z (NOTE: 0.5, not 5. see below),
              0, 0, 0,   //looking at a 0.5x0.5 X/Y quad at the origin
              0, 1, 0    //rotated such that +Y is up
             );
    

    The other issue is that gluLookAt shouldn't be applied to the projection matrix. It'll work for now but will break lighting later. Move it to the modelview matrix:

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    gluLookAt(... as before ...);
    

    Assuming the projection matrix hasn't been set, changing the from position of gluLookAt back to your 5 will make the quad disappear. This is because the default projection gives a viewing volume of an orthographic -1 to 1 cube. With the "camera" now too far away it won't see anything. This is where you'll want to investigate changing the projection matrix. Maybe increase the size of the orthographic projection with glOrtho(), or look into the more complex but natural gluPerspective().