SDL - C++ 中 LoopTimer 的 FPS 问题

SDL - FPS problems with LoopTimer in c++

本文关键字:FPS 问题 LoopTimer C++ SDL      更新时间:2023-10-16

我们正在为我们的 c++ 类制作一个游戏引擎,除了我们在 FPS 上遇到了一些小问题之外,我们基本上完成了所有工作。它的运行速度总是比我们设置的慢 10-20%,我们想知道这是由于错误/蹩脚的代码还是它就是这样?如果我们将其设置为 350+,则上限为 500,但这主要是由于计算机无法处理更多。如果我们将其设置为 50,则得到大约 40-44。

下面是处理计时器的 LoopTimer 类中的一些片段

页眉:

class LoopTimer {
public:
    LoopTimer(const int fps = 50);
    ~LoopTimer();
    void Update();
    void SleepUntilNextFrame();
    float GetFPS() const;
    float GetDeltaFrameTime() const { return _deltaFrameTime; }
    void SetWantedFPS(const int wantedFPS);
    void SetAccumulatorInterval(const int accumulatorInterval);
private:
    int _wantedFPS;
    int _oldFrameTime;
    int _newFrameTime;
    int _deltaFrameTime;
    int _frames;
    int _accumulator;
    int _accumulatorInterval;
    float _averageFPS;
};

CPP 文件

LoopTimer::LoopTimer(const int fps)
{
    _wantedFPS = fps;
    _oldFrameTime = 0;
    _newFrameTime = 0;
    _deltaFrameTime = 0;
    _frames = 0;
    _accumulator = 0;
    _accumulatorInterval = 1000;
    _averageFPS = 0.0;
}
void LoopTimer::Update()
{
    _oldFrameTime = _newFrameTime;
    _newFrameTime = SDL_GetTicks();
    _deltaFrameTime = _newFrameTime - _oldFrameTime;
    _frames++;
    _accumulator += _deltaFrameTime;
    if(_accumulatorInterval < _accumulator)
    {
        _averageFPS = static_cast<float>(_frames / (_accumulator / 1000.f));
        //cout << "FPS: " << fixed << setprecision(1) << _averageFPS << endl;
        _frames = 0;
        _accumulator = 0;
    }
}

void LoopTimer::SleepUntilNextFrame()
{
    int timeThisFrame = SDL_GetTicks() - _newFrameTime;
    if(timeThisFrame < (1000 / _wantedFPS))
    {
        // Sleep the remaining frame time.
        SDL_Delay((1000 / _wantedFPS) - timeThisFrame);
    }
}

该更新基本上是在我们的游戏管理器中以运行方法调用的:

int GameManager::Run()
{
while(QUIT != _gameStatus)
    {
        SDL_Event ev;
        while(SDL_PollEvent(&ev))
    {
            _HandleEvent(&ev);
    }
    _Update();
    _Draw();
    _timer.SleepUntilNextFrame();
   }    
    return 0;
}

如果需要,我可以提供更多代码,或者我很乐意将代码分发给可能需要它的任何人。有很多事情要做,包括sdl_net函数等等,所以没有必要把它们全部转储到这里。

无论如何,我希望有人对帧率有一个聪明的提示,要么如何改进它,要么是不同的循环计时器功能,要么只是告诉我 fps 有小幅损失是正常的:)

我认为你的功能有错误

int timeThisFrame = /* do you mean */ _deltaFrameTime;  //SDL_GetTicks() - _newFrameTime;