Quaternion

Represents a rotation in 3D space. Quaternions avoid gimbal lock and allow smooth interpolation.

using Xengine.Math;

Static Values

ConstantDescription
Quaternion.IdentityNo rotation (default)

Creating Rotations

FromAxisAngle

static Quaternion FromAxisAngle(Vector3 axis, float angleDegrees)
// Rotate 90 degrees around Y axis
var rotation = Quaternion.FromAxisAngle(Vector3.Up, 90f);

FromEulerAngles

static Quaternion FromEulerAngles(float pitch, float yaw, float roll)
// Create from pitch, yaw, roll (in degrees)
var rotation = Quaternion.FromEulerAngles(0, 45, 0);

FromEulerAngles (Vector3)

static Quaternion FromEulerAngles(Vector3 eulerAngles)
var rotation = Quaternion.FromEulerAngles(new Vector3(0, 45, 0));

LookRotation

static Quaternion LookRotation(Vector3 forward, Vector3 up)
// Face towards target
var direction = (target - position).Normalized;
var rotation = Quaternion.LookRotation(direction, Vector3.Up);

Properties

PropertyTypeDescription
X, Y, Z, WfloatQuaternion components
EulerAnglesVector3Get/set as euler angles
NormalizedQuaternionUnit quaternion
ConjugateQuaternionInverse rotation

Methods

Slerp

static Quaternion Slerp(Quaternion a, Quaternion b, float t)

Spherical interpolation between two rotations. Use for smooth rotation.

// Smooth rotation towards target
rotation = Quaternion.Slerp(rotation, targetRotation, 5f * Time.Delta);

Lerp

static Quaternion Lerp(Quaternion a, Quaternion b, float t)

Linear interpolation. Faster than Slerp but less accurate for large rotations.

Inverse

static Quaternion Inverse(Quaternion q)
var inverseRotation = Quaternion.Inverse(rotation);

Operators

// Combine rotations
var combined = rotationA * rotationB;

// Rotate a vector
Vector3 rotatedPoint = rotation * point;

Common Patterns

Rotate Over Time

protected override void OnUpdate()
{
    // Rotate 90 degrees per second around Y axis
    var rotationDelta = Quaternion.FromAxisAngle(Vector3.Up, 90f * Time.Delta);
    Transform.Rotation = Transform.Rotation * rotationDelta;
}

Look At Target

protected override void OnUpdate()
{
    var target = Scene.FindByName("Target");
    if (target == null) return;
    
    var direction = (target.Transform.Position - Transform.Position).Normalized;
    var targetRotation = Quaternion.LookRotation(direction, Vector3.Up);
    
    // Smooth rotation
    Transform.Rotation = Quaternion.Slerp(Transform.Rotation, targetRotation, 5f * Time.Delta);
}

Oscillating Rotation

protected override void OnUpdate()
{
    float angle = MathF.Sin(Time.Now * 2f) * 30f; // +/- 30 degrees
    Transform.Rotation = Quaternion.FromAxisAngle(Vector3.Up, angle);
}