Trying to get OpenGL to follow object without using lookat() C++

I have a ball that stays (off) centered on the screen with a terrain that can rotate under it. I want to follow it with a camera that is a set distance from behind and this is my necessary code already:

ball= glm::scale(ball, scale);
ball1 = glm::translate(ball1, glm::vec3(0.0f, 0.0f, -2.5f + zdepthball));
view = glm::inverse(ball) * ball1;

here is the keypress code:

if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
{
	zdepthball =  zdepthball - .0005f;
	c_mycamera.position += c_mycamera.front * velocity;

because the view has an inverse and multiplication I don’t think I can use a lookat() type statement.

The closest solution I have seen is this :

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

here is the link to the current workings:

https://youtu.be/As3weWMJD-U

could someone show me this trick please, thank you,

Josh

EDIT: a longer video :

https://youtu.be/ry-tkE-Vz5E

To save yourself dev time, think generally. Then plug in the specific example.

General solution:

  1. Generate a modeling transform for each object (including the camera) to place them in world-space (M1, M2, M3, etc.).
  2. Invert your camera’s modeling transform. That’s your viewing transform.

Now plug in your specific scenario:

  1. M1 places the ball in the world
  2. M2 places the camera into the world
  3. V = M2.inverse()

In your case, M2=M1*T, where T is a translate relative to the ball’s local coordinate frame.

1 Like