Search code examples
openglglulookat

gluLookAt() not looking where it should


I don't understand what the glLookAt() function does exactly.

I have an object at position x,y,z . I want to place the camera at position x+20,y+20,z+20 while the object is moving, so that it should look like stationary. However, this is not the case : when I do the following code, I see a cross which is slowly moving to the right and even goes out of the window !

while (keystate[SDLK_ESCAPE] == false) {

SDL_PollEvent(&event);

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

n+=0.1;
float x = 10;
float y = 10+n*n;
float z = 10;

// drawing an object at x,y,z (here a cross)
glBegin(GL_LINES);
glColor3ub(200,0,0);
glVertex3f(x-2,y,z);
glVertex3f(x+2,y,z);
glVertex3f(x,y-2,z);
glVertex3f(x,y+2,z);
glEnd();

// looking at the object
glMatrixMode( GL_MODELVIEW );
glLoadIdentity( );
gluLookAt(x+20,y+20,z+20,x,y,z,0,0,1);

glFlush();
SDL_GL_SwapBuffers();

}

If the camera were correctly looking at x,y,z , the cross should always appear at the center ?

If I put y = 10 + n , the object looks stationary. With y = 10 + n * n , the object moves at constant speed, and with y = 10 + n * n * n, the object moves and accelerates.

I also did

gluPerspective(70,(double)640/480,1,1000);

at the beginning of my code.

Thank you in advance ! :S


Solution

  • OpenGL is a state machine, not a scene graph library. It does not remember the objects you have drawn. With your code, you first draw the object (with whatever matrices are current), and after that, set the new view matrix. This will have no effect on the object already drawn during this frame.

    When the above code is executed in a loop, this will have the effect that the camera always looks at the object's position from last frame, and as faster your object is moving, the more away from the camera it will get.

    Set the matrices before you draw the object.