THREE.js | TWEEN.js | Rotate Camera smoothly

1.2k views Asked by At

At the start of the program, my camera looks at the point (0,0,0). I increase the z-coordinate of the camera as I scroll down. When it hits 160, I want to rotate the camera to look at the point (0,0,300) where an object is placed. I used cameraLookAt(), but the transition was too abrupt. I learnt about TWEEN.js and tried implementing it. But it doesn't seem to be doing anything.

Please help.

  if (camera.position.z > 160) {

      var startRotation = new THREE.Euler().copy( camera.rotation );

      var endRotation = new THREE.Euler().copy( 0, 0, 300 );

      var tween = new TWEEN.Tween( startRotation ).to( { rotation: endRotation }, 2000 )

      tween.onUpdate(() => {
        camera.lookAt(startRotation)
      })

      tween.start()

    }
1

There are 1 answers

4
Mugen87 On

There is no need to use an animation library for this use case. Yes, lookAt() will directly orient the camera towards a specified target. However, you can use Quaternion.rotateTowards() to perform the orientation gradually. This method is similar to Unity's Quaternion.RotateTowards(). There is also an example that demonstrates this approach:

https://threejs.org/examples/webgl_math_orientation_transform

The idea is to compute a target orientation for your camera and then use rotateTowards() in the animation loop. The target orientation is endRotation in your app. You just need it as a quaternion. Try it with:

const endRotation = new THREE.Quaternion().setFromEuler( new THREE.Euler( 0, 0, 300 ) );