A quaternion is a mathematical representation used to describe 3D rotations in a way that avoids the "gimbal lock" problem associated with Euler angles.
In Godot, quaternions are implemented through the Quaternion class and provide a compact, efficient way to represent orientations in 3D space.
Quaternions store rotation as four values, (x, y, z, w)
:
- The first three,
(x, y, z)
, control the axis of rotation.
w
determines the angle of rotation around that axis.
These values are not angles!The values of a quaternion are not angles like the x, y, and z values of Euler angles. They are not exactly like an arbitrary vector either.The way the values work is a bit more complex. That said, in practice, you do not need to understand the values to use them effectively in Godot. You'll work with functions that convert between quaternions and other representations, like Euler angles or transform matrices.
Here's a breakdown of how quaternions work:
- Let's define a unit vector (a vector with a length of 1.0) representing the desired axis of rotation. This vector is usually defined like this:
n = (nx, ny, nz)
, where nx
, ny
, and nz
are the components of the vector.
- We'll name the rotation angle around the vector
n
as theta
. It's the desired angle of rotation in radians.
Here's how we can convert this information into a quaternion:
w = cos(theta / 2)
x = nx * sin(theta / 2)
y = ny * sin(theta / 2)
z = nz * sin(theta / 2)
While less intuitive than Euler angles (pitch, yaw, roll), quaternions give you smooth and lock-free interpolation between rotations (we call that spherical-lerp or "slerp" for short). They don't have the Gimbal lock issue that Euler angles do, which means you can smoothly rotate between any two orientations without running into problems where the rotation axes align and prevent rotation.See Also
Related terms in the Glossary