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

一个人想着一个人 提交于 2019-12-18 13:36:35

问题


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;
    }
}

回答1:


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



回答2:


The answer to that is simple. You have player controlled object (car) so you have its position and orientation via ModelViewMatrix in world space (usualy pointed to the center of 3D model) To transform it to the correct follow ProjectionMatrix you must:

  1. obtain car ModelViewMatrix to double M[16]
  2. translate/rotate it to the new position (inside cockpit or behind car) so the Z axis is pointing the way you want to see.
  3. Invert M ... M=Inverse(M)
  4. Apply perspective M=M*PerspectiveMatrix
  5. store M as ProjectionMatrix before rendering

for additional stuff you need look at my answer here: https://stackoverflow.com/a/18041433/2521214



来源:https://stackoverflow.com/questions/6171092/how-to-make-camera-follow-a-3d-object-in-opengl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!