2
votes

I'm working on a simple 2D top-down OpenGL game in which the camera follows the player. I use gluLookAt to position the camera above the player and look in its direction. However, while running the game, the camera keeps rotating around an axis, even if no input is given.

The speed of rotation depends on the distance between the player and the origin, but printing the values I pass to gluLookAt confirms that they are not being changed when the camera rotates. So how do the camera parameters change when no new values are being passed to it?

Updating the eye coordinates rotates the 2D game plane around its axes, updating the lookat coordinates rotates the camera around its own axes, and updating the up-direction (using mouse coordinates) makes the game spin in-plane.

I have a glutMainLoop with a callback to the render function as displayFunc and idleFunc. The render function (which doubles as the game tick) is as follows:

void render()
{
    gameTick();

    // Move camera
    printf("pos: %.2f, %.2f, %.2f\tlookat: %.2f, %.2f, %.2f\n", player.pos.x, player.pos.y, 0.0f, 0.0, 0.0, -5.0);
    gluLookAt(
        //player.pos.x, player.pos.y, 0.0f,
        0.0,0.0,0.0,
        //player.pos.x, player.pos.y, -5.0f,
        0.0, 0.0, -5.0,
        0.0, 1.0, 0.0
    );

    // Clearing buffer
    glClearColor(g_backgroundColor.getR(), g_backgroundColor.getG(), g_backgroundColor.getB(), 1.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    // Drawing enemies
    for (size_t i = 0; i < agents.size(); i++)
        drawSquare(agents[i].pos, agents[i].ori, g_enemyColor);

    // Drawing player
    drawSquare(player.pos, player.ori, g_playerColor);

    glutSwapBuffers();
}

The camera is at z=0, and the game plane at z=-5.

Am I missing an essential OpenGL call after updating the camera or something?

1

1 Answers

3
votes

gluLookAt doesn't only define a view matrix.
It defines a matrix, and multiplied the current matrix by the new matrix.

Set the Identity matrix before calling gluLookAt by glLoadIdentity, to solve the issue:

glMatrixMode(GL_MODEL_VIEW);
glLoadIdentity();
gluLookAt(
    //player.pos.x, player.pos.y, 0.0f,
    0.0,0.0,0.0,
    //player.pos.x, player.pos.y, -5.0f,
    0.0, 0.0, -5.0,
    0.0, 1.0, 0.0
);