• 🗿 raylib rmodels — 3D 模型与网格示例(C 语言)

    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"

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

    // --- 摄像机设置 ---
    Camera3D camera = { 0 };
    camera.position = (Vector3){ 4.0f, 4.0f, 4.0f }; // 摄像机位置
    camera.target = (Vector3){ 0.0f, 1.0f, 0.0f }; // 看向模型中心
    camera.up = (Vector3){ 0.0f, 1.0f, 0.0f }; // 上方向
    camera.fovy = 45.0f;
    camera.projection = CAMERA_PERSPECTIVE;

    // --- 加载模型(OBJ) ---
    Model model = LoadModel("resources/cube.obj");

    // --- 加载纹理并贴图 ---
    Texture2D texture = LoadTexture("resources/cube_diffuse.png");
    model.materials[0].maps[MATERIAL_MAP_DIFFUSE].texture = texture;

    // 模型位置
    Vector3 position = { 0.0f, 0.0f, 0.0f };

    float rotation = 0.0f;

    while (!WindowShouldClose())
    {
    rotation += 60.0f * GetFrameTime(); // 每秒旋转 60 度

    BeginDrawing();
    ClearBackground(RAYWHITE);

    BeginMode3D(camera);

    // 绘制模型(带旋转)
    DrawModelEx(model, position,
    (Vector3){0, 1, 0}, // 绕 Y 轴旋转
    rotation,
    (Vector3){1, 1, 1}, // 缩放
    WHITE);

    DrawGrid(20, 1.0f); // 地面网格

    EndMode3D();

    DrawText("3D model loaded with texture", 10, 10, 20, DARKGRAY);

    EndDrawing();
    }

    // 卸载资源
    UnloadTexture(texture);
    UnloadModel(model);

    CloseWindow();
    return 0;
    }

    📌 示例中使用的 rmodels API

    功能 API
    加载模型 LoadModel()
    卸载模型 UnloadModel()
    加载纹理 LoadTexture()
    贴图到模型 model.materials[0].maps[MATERIAL_MAP_DIFFUSE].texture = texture
    绘制模型 DrawModel() / DrawModelEx()
    绘制网格 DrawGrid()

    这些 API 就能加载 OBJ、GLTF、IQM 等 3D 模型。