Skip to content

quat

A four-dimensional complex number used to represent 3D rotations. Quaternions are used for rotation because they avoid gimbal lock and support smooth interpolation.

Initialize a rotation using common spatial concepts.

-- identity rotation (no rotation)
local q1 = quat()
-- rotate 90 degrees (pi/2) around the Y (up) axis
local q2 = quat.fromAngleAxis(math.pi / 2, vec3(0, 1, 0))
-- rotation representing looking toward a specific direction
local q3 = quat.fromDirection(vec3(1, 0, 1))

In CSP, the quat primitive is primarily used to define the orientation of nodes, cameras, and physical rigid bodies.

A quaternion can rotate a vec3 by multiplication (for example, rotated = quat * vec3). Multiplying two quaternions combines their rotations, but order matters: q1 * q2 does not produce the same result as q2 * q1.

For interpolation, the :slerp() method allows for smooth transitions between orientations at a constant angular velocity, making it the preferred approach for animated rotations.

PropertyTypeDescription
xnumberThe imaginary X component.
ynumberThe imaginary Y component.
znumberThe imaginary Z component.
wnumberThe real (scalar) W component.
MethodDescription
:setAngleAxis(angle, axis)Updates the quaternion to represent a rotation around an axis (radians).
:getAngleAxis()Returns the angle and the axis vector representing the rotation.
:normalize(out)Ensures the quaternion has a length of 1 (required for valid rotations).
:mul(other, out)Multiplies two quaternions to combine rotations.
:slerp(target, mix, out)Performs a smooth spherical interpolation toward a target rotation.
:clone()Creates a copy of the quaternion.

Taking a “Forward” vector and rotating it 45 degrees to the side.

local forward = vec3(0, 0, 1)
local rotation = quat.fromAngleAxis(math.rad(45), vec3(0, 1, 0))
-- rotate the vector
local sideView = rotation * forward