🎯 raymath — C 语言示例(最常用功能)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include "raylib.h"
#include "raymath.h"

int main(void)
{
InitWindow(800, 450, "raymath example");
SetTargetFPS(60);

// --- 向量示例 ---
Vector3 a = { 1.0f, 2.0f, 3.0f };
Vector3 b = { 4.0f, 5.0f, 6.0f };

Vector3 add = Vector3Add(a, b);
Vector3 sub = Vector3Subtract(a, b);
Vector3 mul = Vector3Multiply(a, b);
Vector3 norm = Vector3Normalize(a);

float dot = Vector3DotProduct(a, b);
Vector3 cross = Vector3CrossProduct(a, b);

// --- 矩阵示例 ---
Matrix matTranslate = MatrixTranslate(2.0f, 0.0f, 0.0f);
Matrix matRotate = MatrixRotateY(PI / 4);
Matrix matScale = MatrixScale(2.0f, 2.0f, 2.0f);

Matrix matTransform = MatrixMultiply(MatrixMultiply(matTranslate, matRotate), matScale);

// --- 四元数示例 ---
Quaternion q1 = QuaternionFromEuler(0.0f, PI/4, 0.0f);
Quaternion q2 = QuaternionFromEuler(0.0f, PI/2, 0.0f);
Quaternion qLerp = QuaternionLerp(q1, q2, 0.5f);

// --- 插值示例 ---
float v = Lerp(0.0f, 100.0f, 0.25f); // 25

// --- 角度/弧度 ---
float rad = DEG2RAD * 90.0f;
float deg = RAD2DEG * PI;

while (!WindowShouldClose())
{
BeginDrawing();
ClearBackground(RAYWHITE);

DrawText("raymath C example", 20, 20, 20, DARKBLUE);

DrawText(TextFormat("Vector3Add: (%.1f, %.1f, %.1f)", add.x, add.y, add.z), 20, 70, 20, DARKGRAY);
DrawText(TextFormat("Dot: %.2f", dot), 20, 100, 20, DARKGRAY);
DrawText(TextFormat("Cross: (%.1f, %.1f, %.1f)", cross.x, cross.y, cross.z), 20, 130, 20, DARKGRAY);

DrawText(TextFormat("Lerp(0,100,0.25)= %.1f", v), 20, 170, 20, DARKGRAY);
DrawText(TextFormat("90 deg = %.2f rad", rad), 20, 200, 20, DARKGRAY);

EndDrawing();
}

CloseWindow();
return 0;
}

🧠 会用到的 raymath 核心函数(速查表)

✔ 向量(Vector2 / Vector3)

  • Vector3Add(a, b)
  • Vector3Subtract(a, b)
  • Vector3Scale(v, s)
  • Vector3Normalize(v)
  • Vector3DotProduct(a, b)
  • Vector3CrossProduct(a, b)
  • Vector3Distance(a, b)
  • Vector3Lerp(a, b, t)

✔ 矩阵(Matrix)

  • MatrixTranslate(x, y, z)
  • MatrixRotateX(angle)
  • MatrixRotateY(angle)
  • MatrixRotateZ(angle)
  • MatrixScale(x, y, z)
  • MatrixMultiply(a, b)
  • MatrixLookAt(eye, target, up)
  • MatrixPerspective(fovy, aspect, near, far)

✔ 四元数(Quaternion)

  • QuaternionFromEuler(x, y, z)
  • QuaternionToEuler(q)
  • QuaternionMultiply(a, b)
  • QuaternionLerp(a, b, t)
  • QuaternionSlerp(a, b, t)

✔ 角度/弧度

  • DEG2RAD
  • RAD2DEG

✔ 插值

  • Lerp(a, b, t)
  • Clamp(value, min, max)
  • SmoothStep(a, b, t)

🎮 这些 raymath 功能在游戏里怎么用?

  • 摄像机旋转 → Quaternion + MatrixRotate
  • 角色移动 → Vector3Add / Normalize
  • 子弹方向 → Vector3Normalize
  • 碰撞检测 → Vector3Distance
  • 动画插值 → Lerp / QuaternionSlerp
  • 模型变换 → MatrixTranslate + Rotate + Scale