87 lines
2.1 KiB
Markdown
87 lines
2.1 KiB
Markdown
|
|
# Quaternion
|
||
|
|
|
||
|
|
四元数结构体,用于表示 3D 旋转,避免欧拉角的万向锁问题。
|
||
|
|
|
||
|
|
## 头文件
|
||
|
|
|
||
|
|
```cpp
|
||
|
|
#include <XCEngine/Math/Quaternion.h>
|
||
|
|
```
|
||
|
|
|
||
|
|
## 命名空间
|
||
|
|
|
||
|
|
`XCEngine::Math`
|
||
|
|
|
||
|
|
## 结构体定义
|
||
|
|
|
||
|
|
```cpp
|
||
|
|
struct Quaternion {
|
||
|
|
float x = 0.0f;
|
||
|
|
float y = 0.0f;
|
||
|
|
float z = 0.0f;
|
||
|
|
float w = 1.0f; // w 是标量分量
|
||
|
|
};
|
||
|
|
```
|
||
|
|
|
||
|
|
四元数格式: `(x, y, z, w)` = `(vec, w)`
|
||
|
|
|
||
|
|
## 静态工厂方法
|
||
|
|
|
||
|
|
| 方法 | 返回值 | 描述 |
|
||
|
|
|------|--------|------|
|
||
|
|
| `Identity()` | `Quaternion` | 返回 (0, 0, 0, 1),恒等旋转 |
|
||
|
|
| `FromAxisAngle(axis, radians)` | `Quaternion` | 从轴角创建 |
|
||
|
|
| `FromEulerAngles(pitch, yaw, roll)` | `Quaternion` | 从欧拉角创建(弧度) |
|
||
|
|
| `FromEulerAngles(euler)` | `Quaternion` | 从 Vector3 欧拉角创建 |
|
||
|
|
| `FromRotationMatrix(matrix)` | `Quaternion` | 从旋转矩阵创建 |
|
||
|
|
| `Slerp(a, b, t)` | `Quaternion` | 球面线性插值 |
|
||
|
|
| `LookRotation(forward, up)` | `Quaternion` | 看向方向 |
|
||
|
|
|
||
|
|
## 实例方法
|
||
|
|
|
||
|
|
| 方法 | 返回值 | 描述 |
|
||
|
|
|------|--------|------|
|
||
|
|
| `ToEulerAngles()` | `Vector3` | 转换为欧拉角(弧度) |
|
||
|
|
| `ToMatrix4x4()` | `Matrix4` | 转换为 4x4 旋转矩阵 |
|
||
|
|
| `Inverse()` | `Quaternion` | 共轭/逆四元数 |
|
||
|
|
| `Dot(other)` | `float` | 点积 |
|
||
|
|
| `Magnitude()` | `float` | 模长 |
|
||
|
|
| `Normalized()` | `Quaternion` | 归一化 |
|
||
|
|
| `Normalize(q)` | `Quaternion` | 归一化(静态) |
|
||
|
|
|
||
|
|
## 运算符
|
||
|
|
|
||
|
|
| 运算符 | 描述 |
|
||
|
|
|--------|------|
|
||
|
|
| `operator*(Quaternion, Quaternion)` | 组合旋转 |
|
||
|
|
|
||
|
|
## 与 Vector3 的乘法
|
||
|
|
|
||
|
|
```cpp
|
||
|
|
Vector3 operator*(const Quaternion& q, const Vector3& v);
|
||
|
|
```
|
||
|
|
用四元数旋转向量。
|
||
|
|
|
||
|
|
## 使用示例
|
||
|
|
|
||
|
|
```cpp
|
||
|
|
// 创建旋转
|
||
|
|
Quaternion rot = Quaternion::FromEulerAngles(0.0f, 90.0f * DEG_TO_RAD, 0.0f);
|
||
|
|
|
||
|
|
// 组合旋转
|
||
|
|
Quaternion combined = rot1 * rot2;
|
||
|
|
|
||
|
|
// 球面插值
|
||
|
|
Quaternion lerped = Quaternion::Slerp(rot1, rot2, 0.5f);
|
||
|
|
|
||
|
|
// 旋转向量
|
||
|
|
Vector3 rotated = rot * Vector3::Forward();
|
||
|
|
|
||
|
|
// 转换
|
||
|
|
Vector3 euler = rot.ToEulerAngles();
|
||
|
|
Matrix4 mat = rot.ToMatrix4x4();
|
||
|
|
|
||
|
|
// 看向目标
|
||
|
|
Quaternion lookAt = Quaternion::LookRotation(target - position);
|
||
|
|
```
|