Rotation Quaternions
Transformations
Rotation Quaternions
A quaternion is a four-dimensional vector (x, y, z, w), and to be a rotation quaternion it has to be a unit vector; i.e. x2 + y2 + z2 + w2 = 1.
We have already used rotate, which sets the rotation quaternion of a mesh.
You can check this in the console:
import { Space } from "@babylonjs/core/Maths/math.axis";import { Vector3 } from "@babylonjs/core/Maths/math.vector";mesh.rotate(new Vector3(1, 0 - 1), Math.PI / 3, Space.WORLD);console.log(mesh.rotationQuaternion.x);console.log(mesh.rotationQuaternion.y);console.log(mesh.rotationQuaternion.z);console.log(mesh.rotationQuaternion.w);Like the rotation property, the rotationQuaternion property sets the orientation of the mesh with the local origin as the center of rotation.
Besides rotate you can also obtain a rotation quaternion directly by using, for example
import { Quaternion, Vector3 } from "@babylonjs/core/Maths/math.vector";mesh.rotationQuaternion = new Quaternion.RotationAxis(new Vector3(1, 0, -1), Math.PI / 3);The parameters for the RotationAxis method are axis direction and angle. The axis direction vector should be expressed in the world space.
Any rotation quaternion can be converted to Euler angles for use with mesh.rotation:
const euler = rotation_quaternion.toEulerAngles();Showing that converted Euler angles to and from rotation quaternion align. Converting Euler to Quaternion Alignment
You can also change the orientation of a mesh using a number of different conventions.
Warning
You cannot use a rotationQuaternion followed by a rotation on the same mesh. Once a rotationQuaternion is applied, any subsequent use of rotation will produce the wrong orientation unless the rotationQuaternion is first set to null. Please be aware that this often applies when importing models, as many of them already have a rotationQuaternion set.
From version 4.0 onward, rotationQuaternion is set to null automatically when, and only when, rotation is set directly with a vector, for example:
import { Vector3 } from "@babylonjs/core/Maths/math.vector";mesh.rotation = new Vector3(0, 0, 0);Whenever you find rotation errors it is worth setting rotationQuaternion to null before updating rotation.