raylib 时间控制示例(C 语言)

这个示例展示:

  • 固定帧率(SetTargetFPS)
  • 获取上一帧耗时(GetFrameTime)
  • 获取程序运行时间(GetTime)
  • 用 DeltaTime 做平滑移动(推荐做法)
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
#include "raylib.h"

int main(void)
{
InitWindow(800, 450, "raylib time control example");

SetTargetFPS(60); // 固定帧率为 60 FPS

float x = 100.0f; // 一个小球的 x 坐标
float speed = 200.0f; // 每秒移动 200 像素

while (!WindowShouldClose())
{
// --- 时间控制 ---
float dt = GetFrameTime(); // 上一帧耗时(秒)
float t = GetTime(); // 程序运行总时间(秒)

// --- 使用 DeltaTime 做平滑移动 ---
x += speed * dt;

if (x > GetScreenWidth()) x = 0;

BeginDrawing();
ClearBackground(RAYWHITE);

DrawCircle((int)x, 200, 20, RED);

DrawText(TextFormat("dt = %.4f sec", dt), 10, 10, 20, DARKGRAY);
DrawText(TextFormat("time = %.2f sec", t), 10, 40, 20, DARKGRAY);
DrawText("Ball moves smoothly using DeltaTime", 10, 70, 20, DARKGRAY);

EndDrawing();
}

CloseWindow();
return 0;
}