Overview
Quaternions are a mathematical construct used to represent rotations in three‑dimensional space. In DirectX, they provide a compact and numerically stable way to interpolate orientations, avoid gimbal lock, and compose rotations efficiently.
Syntax
struct XMFLOAT4
{
float x; // i component
float y; // j component
float z; // k component
float w; // real component
};
typedef XMFLOAT4 XQuaternion;
The XQuaternion
type is defined as an XMFLOAT4
where (x, y, z)
represent the vector part and w
is the scalar part.
Common Functions
Function | Purpose |
---|---|
XMQuaternionRotationRollPitchYaw | Creates a quaternion from Euler angles (pitch, yaw, roll). |
XMQuaternionMultiply | Combines two rotations. |
XMQuaternionConjugate | Returns the inverse rotation for unit quaternions. |
XMQuaternionSlerp | Spherical linear interpolation between two quaternions. |
XMQuaternionToRollPitchYaw | Extracts Euler angles from a quaternion. |
Example: Rotating a Cube
#include <DirectXMath.h>
using namespace DirectX;
XQuaternion q = XMQuaternionRotationRollPitchYaw(pitch, yaw, roll);
XMMATRIX rotMatrix = XMMatrixRotationQuaternion(q);
XMMATRIX world = rotMatrix * XMMatrixTranslation(pos.x, pos.y, pos.z);
This snippet demonstrates creating a quaternion from Euler angles, converting it to a rotation matrix, and applying a translation to form a world matrix for rendering a 3‑D cube.
Quaternion Calculator
Remarks
- Always normalize quaternions before using them for interpolation or as rotation representations.
- When concatenating rotations, multiply quaternions in the order
qResult = q2 * q1
, whereq1
is applied first. - Quaternions are more efficient than matrices for smooth interpolation but must be converted to matrices for most shader pipelines.