Overview
Quaternions provide a compact, non‑gimbal‑locking representation for 3‑D rotations. In DirectXMath they are represented by the XMFLOAT4
and XMVECTOR
types, typically interpreted as (x, y, z, w)
where w
is the scalar part.
Basics
Creating a quaternion from an axis‑angle, converting to/from rotation matrices, and normalizing are common operations.
// Create a quaternion representing a 45° rotation around Y axis
XMVECTOR axis = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);
float angle = XMConvertToRadians(45.0f);
XMVECTOR q = XMQuaternionRotationAxis(axis, angle);
// Normalize
q = XMQuaternionNormalize(q);
Common Operations
- Multiplication (composition):
XMQuaternionMultiply(q1, q2)
- Slerp (spherical linear interpolation):
XMQuaternionSlerp(q1, q2, t)
- Conjugate:
XMQuaternionConjugate(q)
- Inverse:
XMQuaternionInverse(q)
- Convert to rotation matrix:
XMMatrixRotationQuaternion(q)
- Transform a vector:
XMVector3Rotate(v, q)
C++ Example: Rotating a Model
#include <DirectXMath.h>
using namespace DirectX;
void Update(float deltaTime, XMFLOAT4& quat)
{
// Rotate 30°/sec around the X axis
static const XMVECTOR axis = XMVectorSet(1,0,0,0);
float angle = XMConvertToRadians(30.0f) * deltaTime;
XMVECTOR delta = XMQuaternionRotationAxis(axis, angle);
XMVECTOR q = XMLoadFloat4(&quat);
q = XMQuaternionMultiply(q, delta);
q = XMQuaternionNormalize(q);
XMStoreFloat4(&quat, q);
}