在 c++ 中调整帧速率的简单方法是什么?

What's the simples way of adjusting frame rate in c++?

本文关键字:简单 方法 是什么 帧速率 c++ 调整      更新时间:2023-10-16

我有一个while循环,它使用openGL在窗口上显示内容,但与在其他计算机上运行的方式相比,动画太快了,所以我需要在循环中有一些东西,它只允许在上次显示后显示1/40秒,我该怎么做?(我是c++noob)

您需要在循环开始时检查时间,在完成所有渲染和更新逻辑后,在循环结束时再次检查时间,然后Sleep()检查所用时间与目标帧时间之间的差异(每秒40帧,25毫秒)。

这是我在C++和SDL库中使用的一些代码。基本上,您需要有一个函数在循环开始时启动计时器(StartFpsTimer()),以及一个函数根据您想要的恒定帧速率等待足够的时间直到下一帧到期(WaitTtillNextFrame())。

m_oTimer对象是一个简单的计时器对象,可以启动、停止和暂停。GAME_ENGINE_FPS是您想要的帧速率。

// Sets the timer for the main loop
void StartFpsTimer()
{
    m_oTimer.Start();
}
// Waits till the next frame is due (to call the loop at regular intervals)
void WaitTillNextFrame()
{
    if(this->m_oTimer.GetTicks() < 1000.0 / GAME_ENGINE_FPS) {
        delay((1000.0 / GAME_ENGINE_FPS) - m_oTimer.GetTicks());
    }
}
while (this->IsRunning())
{
    // Starts the fps timer
    this->StartFpsTimer();
    // Input
    this->HandleEvents();
    // Logic
    this->Update();
    // Rendering
    this->Draw();
    // Wait till the next frame
    this->WaitTillNextFrame();
}