Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to make camera follow a 3d object in opengl?

i'm making a car race for the first time using opengl,the first problem i face is how to make the camera follow the car with constant distance..here is the code for keyboard function.V is the velocity of the car.

void OnSpecial(int key, int x, int y) 
{
    float step = 5;

    switch(key) {

    case GLUT_KEY_LEFTa:
        carAngle = step;
        V.z = carAngle ;
        camera.Strafe(-step/2);
        break;

    case GLUT_KEY_RIGHT:
        carAngle = -step;
        V.z = carAngle ;
        camera.Strafe(step/2);
        break;

    case GLUT_KEY_UP:
        V.x += (-step);
        camera.Walk(step/2);

        break;
    case GLUT_KEY_DOWN:
        if(V.x<0)
        {
            V.x += step;
            camera.Walk(-step/2);
        }
        break;
    }
}
like image 308
memo Avatar asked May 29 '11 23:05

memo


1 Answers

Something like that maybe ?

vec3 cameraPosition = carPosition + vec3(20*cos(carAngle), 10,20*sin(carAngle));
vec3 cameraTarget = carPosition;
vec3 cameraUp = vec3(0,1,0);

glMatrixMode(GL_MODELVIEW);
glLoadIdentity()
gluLookAt(cameraPosition, cameraTarget, cameraUp);
glTranslate(carPosition);
drawCar();

It you're not using the old and deprecated openGL API (glBegin & stuff) you'll have to do something like

mat4 ViewMatrix = LookAt(cameraPosition, cameraTarget, cameraUp); // adapt depending on what math library you use
like image 119
Calvin1602 Avatar answered Sep 24 '22 18:09

Calvin1602