Three.js How to use Quaternion to rotate a camera

In Three.js, I would like to use THREE.quaternion so that the camera object rotates to the selected object.

I searched on the Internet but did not find an example / demo or document on how to use this quaternion class.

I try using the following code:

camera = new THREE.PerspectiveCamera( 40, window.innerWidth / window.innerHeight, 1, 10000 ); camera.position.y = 10; camera.position.z = 0; camera.position.x = radious; camera.useQuaternion = true; // I did use the TrackballTrackballControls. Maybe it causes the problem so I put it here controls = new THREE.TrackballControls( camera, document.getElementById(_canvasElement) ); // function to make the camera rotate to the object function focusOn3DObject(obj){ obj.useQuaternion = true; obj.quaternion = new THREE.Quaternion(obj.position.x, obj.position.y, obj.position.z, 1); var newQuaternion = new THREE.Quaternion(); THREE.Quaternion.slerp(camera.quaternion, obj.quaternion, newQuaternion, 0.07); camera.quaternion = newQuaternion; } 

But that will not work. Did I miss something? Please help. Thanks in advance.

+9
javascript
source share
3 answers

Slerp is pretty simple. It takes 4 parameters:

  • targetRotation actual camera rotation
  • destinationRotation object rotation
  • destinationRotation new quaternion that will be a new camera twist
  • percentOfRotation This parameter is a playground, I use 0.07 here, there can be a value from 0 (0%) to 1 (100%)

This is my rotation method:

 var qm = new THREE.Quaternion(); THREE.Quaternion.slerp(camera.quaternion, destRotation, qm, 0.07); camera.quaternion = qm; camera.quaternion.normalize(); 

Hope this helps you. And don’t worry, I also worked on the perfect camera for several weeks.

+13
source share

I think this line will not work:

 obj.quaternion = new THREE.Quaternion(obj.position.x, obj.position.y, obj.position.z, 1); 

You need to install

 obj.useQuaternion = true 

After adding an object to the scene when it is rotated, it will be automatically applied to obj.quaternion .

Secondly, you should apply the object to your controls, and not to the camera. Because you want to control an object, not a camera?

+1
source share

You can use the applyQuaternion method from ThreeJs

  const quaternion = new THREE.Quaternion(obj.position.x, obj.position.y, obj.position.z, 1); camera.applyQuaternion(quaternion); // Apply Quaternion camera.quaternion.normalize(); // Normalize Quaternion 
+1
source share

All Articles