Trying to figure out how to make a camera follow an object controlled by physics within a Three.js scene.
I'm currently working on a Three.js scene where the W,A,S,D keys move a sphere along a plane. However, I can't seem to get the camera to follow behind the sphere as it moves.
In the code example below, the camera follows the sphere perfectly when only the W key is pressed. But when A or D are pressed, causing the sphere to turn, the camera loses track of the sphere. My goal is to have the camera always positioned just behind the sphere at a constant distance, even when the sphere turns. As the user continues pressing W, the sphere should keep rolling forward relative to the camera.
In a previous scene demo, I achieved this behavior by creating the sphere, adding it to a group, and using the following code snippet each frame:
var relativeCameraOffset = new THREE.Vector3(0,50,200);
var cameraOffset = relativeCameraOffset.applyMatrix4(sphereGroup.matrixWorld);
camera.position.x = cameraOffset.x;
camera.position.y = cameraOffset.y;
camera.position.z = cameraOffset.z;
camera.lookAt(sphereGroup.position);
The key in the previous demo was to rotate the sphere while keeping the sphereGroup unrotated, allowing me to calculate the camera offset based on the un-rotated sphereGroup.
In the current demo, the sphere's position is influenced by the Cannon.js physics library, which handles translations and rotations based on applied forces. Any ideas on how to make the camera follow the sphere in this setup?
// Code snippets will go here
// CSS snippets will go here
<script src='https://cdnjs.cloudflare.com/ajax/libs/three.js/88/three.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/cannon.js/0.6.2/cannon.js'></script>
Answers to comment questions
@jparimaa Is there a way to implement controls where W adds forward momentum, S adds backward momentum, and A and D control camera rotation around the ball?
@HariV Are there methods to integrate camera logic with physics in Three.js for this scenario?