【问题标题】:Why does this elapsed time (frametime) calculation lockup my game为什么这个经过时间(帧时间)计算会锁定我的游戏
【发布时间】:2019-08-31 08:19:12
【问题描述】:

目前我正在尝试实现一个固定步长的游戏循环,但不知何故我的代码似乎锁定了我的游戏。


Uint32 SDL_GetTicks(void):返回一个无符号的 32 位值,表示自 SDL 库初始化以来的毫秒数。

这行得通:

1.cc)

Uint32 FPS = 60;
Uint32 MS_PER_SEC = 1000 / FPS;
Uint32 current_time, last_time, elapsed_time;
current_time = last_time = elapsed_time = 0;

while(Platform.Poll())
{
    current_time = SDL_GetTicks(); // Get time of frame begin

    // Clear Window
    Renderer.Clear();

    // Update Input
    //...

    // Draw
    Renderer.Draw();

    // Update Window
    Renderer.Update();

    last_time = SDL_GetTicks(); // Get time of frame end
    elapsed_time = last_time - current_time; // calculate frametime

    SDL_Delay(MS_PER_SEC - elapsed_time);
}

但事实并非如此:

2.cc)

Uint32 FPS = 60;
Uint32 MS_PER_SEC = 1000 / FPS;
Uint32 current_time, last_time, elapsed_time;
current_time = elapsed_time = 0;

last_time = SDL_GetTicks();

// Poll for Input
while(Platform.Poll())
{
    current_time = SDL_GetTicks();
    elapsed_time = current_time - last_time;

    // Clear Window
    Renderer.Clear();

    // Update Input
    //...

    // Draw
    Renderer.Draw();

    // Update Window
    Renderer.Update();

    last_time = current_time;
    SDL_Delay(MS_PER_SEC - elapsed_time);
}

我希望 1.cc 和 2.cc 的结果是相同的,这意味着 SDL_Delay(MS_PER_SEC - elapsed_time) 确实会延迟一个固定时间减去帧时间(这里是 16 - 帧时间)。 但是 2.cc 确实锁定了我的游戏。

从 2.cc 计算的 elapsed_time(帧时间)不等于 1.cc 吗?

【问题讨论】:

  • 尝试打印延迟量,看看是否太长?
  • lockup前的延迟时间最后值为18,意思是18ms,对lockup没有意义。编辑:表示延迟时间值。
  • 延迟量是多少?

标签: c++ loops sdl


【解决方案1】:

让我们稍微展开循环......

// First iteration

last_time = SDL_GetTicks();
current_time = SDL_GetTicks();
elapsed_time = current_time - last_time; // Probably zero

...

SDL_Delay(MS_PER_SEC - elapsed_time);    // Probably a whole second

// Second iteration

current_time = SDL_GetTicks();
elapsed_time = current_time - last_time; // Probably slightly more than a whole second

...

SDL_Delay(MS_PER_SEC - elapsed_time);    // Probably negative (4 billion milliseconds)

【讨论】:

  • 你是对的,延迟时间在一段时间后累积到值4294967293。好像溢出了。
【解决方案2】:

该功能基于 RTC,精度非常低,使用时间长,具体取决于平台。 10-30 毫秒的准确度是一个乐观的猜测。

这可能是相关的:SDL_GetTicks() accuracy below the millisecond level

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-25
    • 2020-12-01
    • 2013-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多