What transformation on a quaternion in order for the camera to look in the opposite direction?

So the camera has camera[‘quaternion’] that is looking at a random direction/angle.

What transformation would we need to apply in order to get the quaternion that is looking in the opposite direction (ie: turn the camera 180 degrees)?

Quaternion.invert may be what you’re looking for? :eyes:

Keep in mind:

  1. It mutates the source quaternion, so if you want to keep the original camera quaternion intact, clone it.
  2. It won’t work if you’re using controls - in that case, you just have to move the controls.target to the opposite side of the camera.
1 Like

The quaternion for rotation 180° around Y axis is:

new THREE.Quaternion( 0, 1, 0, 0 );

It might be better to use Quaternion.setFromAxisAngle, as it will make the code easier to understand by people who do not read quaternions:

new THREE.Quaternion().setFromAxisAngle( new THREE.Vector3(0,1,0), Math.PI );

Edit: To apply a quaternion it is multiplied with the object’s quaterion. But as @mjurczyk, this will not work for the camera if you are using e.g. OrbitControls, because the controls will overwrite the camera’s quaternion.

2 Likes

I think this works. But indeed I need to adjust the controls[‘target’] position. Thank you very much!

hmmm, I would think these 2 would give me the same resulting quaternion, but they do not. Note that me camera may be looking at an angle and not necessarily straight ahead. I’ll do some testing with that setFromAxisAngle() method.

    const QUATERNION1 = new THREE.Quaternion();
    const QUATERNION2 = new THREE.Quaternion();

    QUATERNION1.copy(camera['quaternion']);
    QUATERNION2.copy(camera['quaternion']);

    QUATERNION1.invert();
    QUATERNION2.setFromAxisAngle(new THREE.Vector3(0, 1, 0), Math.PI);

    console.log(QUATERNION1);
    console.log(QUATERNION2);

Got to do some more testing by adjusting the controls[‘target’] to me certain this works at any camera angle and not just straight ahead in the Y-axis. :slightly_smiling_face:

The setFromAxisAngle above creates quaternion that is 180° rotation and replaces the already set camera’s quaternion. If you want to apply a quaternion as a relative rotation (i.e. a rotation in addition to already existing rotation), it must be multiplied with the current quaternion. See line 75:

https://codepen.io/boytchev/pen/xxQQPLd?editors=0011

1 Like