我设法创建了一个允许游戏对象根据时间变化(而不是帧数变化)移动的系统。我现在,为了实践,试图强加一个 FPS 限制器。
我遇到的问题是发生的游戏循环数量是我预期的两倍。例如,如果我尝试将帧数限制为 1 FPS,那么 2 帧将在那一秒内通过 - 一个非常长的帧(约 1 秒)和 1 个极短的帧(约 15 毫秒)。这可以通过输出每个游戏循环之间的时间差(以毫秒为单位)来显示 - 示例输出可能是 993、17、993、16...
我尝试更改代码,以便在 FPS 受限之前计算增量时间,但无济于事。
定时器类:
#include "Timer.h"
#include <SDL.h>
Timer::Timer(void)
{
_currentTicks = 0;
_previousTicks = 0;
_deltaTicks = 0;
_numberOfLoops = 0;
}
void Timer::LoopStart()
{
//Store the previous and current number of ticks and calculate the
//difference. If this is the first loop, then no time has passed (thus
//previous ticks == current ticks).
if (_numberOfLoops == 0)
_previousTicks = SDL_GetTicks();
else
_previousTicks = _currentTicks;
_currentTicks = SDL_GetTicks();
//Calculate the difference in time.
_deltaTicks = _currentTicks - _previousTicks;
//Increment the number of loops.
_numberOfLoops++;
}
void Timer::LimitFPS(int targetFps)
{
//If the framerate is too high, compute the amount of delay needed and
//delay.
if (_deltaTicks < (unsigned)(1000 / targetFps))
SDL_Delay((unsigned)(1000 / targetFps) - _deltaTicks);
}
(部分)游戏循环:
//The timer object.
Timer* _timer = new Timer();
//Start the game loop and continue.
while (true)
{
//Restart the timer.
_timer->LoopStart();
//Game logic omitted
//Limit the frames per second.
_timer->LimitFPS(1);
}
注意:我正在使用 SMA 计算 FPS;此代码已被省略。