How to make the camera the next 3D object in opengl?

I am doing a car race for the first time using opengl, the first problem I am facing is how to get the camera to follow the car with a constant distance. Here is the code for the keyboard function. V is the speed of the car.

void OnSpecial(int key, int x, int y) { float step = 5; switch(key) { case GLUT_KEY_LEFTa: carAngle = step; Vz = carAngle ; camera.Strafe(-step/2); break; case GLUT_KEY_RIGHT: carAngle = -step; Vz = carAngle ; camera.Strafe(step/2); break; case GLUT_KEY_UP: Vx += (-step); camera.Walk(step/2); break; case GLUT_KEY_DOWN: if(Vx<0) { Vx += step; camera.Walk(-step/2); } break; } } 
+4
source share
2 answers

Something like this 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(); 

You are not using the old and deprecated OpenGL API (glBegin and so on), you will need to do something like

 mat4 ViewMatrix = LookAt(cameraPosition, cameraTarget, cameraUp); // adapt depending on what math library you use 
+4
source

The answer to this question is simple. You have a player-controlled object (car), so you have your position and orientation using ModelViewMatrix in world space (usually pointing to the center of the 3D model) To convert it to the correct ProjectionMatrix sequence, you must:

  • get ModelViewMatrix to double M [16]
  • move / rotate it to a new position (inside the cab or behind the car) so that the Z axis points as you want to see.
  • Invert M ... M = Inverse (M)
  • Apply Perspective M = M * PerspectiveMatrix
  • save M as ProjectionMatrix before rendering

for the extra material you need, see my answer here: fooobar.com/questions/1355127 / ...

0
source

All Articles