【问题标题】:SDL - FPS problems with LoopTimer in c++SDL - C++ 中 LoopTimer 的 FPS 问题
【发布时间】:2012-04-19 22:35:48
【问题描述】:

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

这是 LoopTimer 类中处理计时器的一些 sn-ps

标题:

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);
    }
}

更新基本上是在我们的 GameManager 中的 run 方法中调用的:

int GameManager::Run()
{
while(QUIT != _gameStatus)
    {
        SDL_Event ev;

        while(SDL_PollEvent(&ev))
    {
            _HandleEvent(&ev);
    }

    _Update();
    _Draw();

    _timer.SleepUntilNextFrame();
   }    
    return 0;
}

如果需要,我可以提供更多代码,或者我很乐意将代码提供给任何可能需要它的人。包括 sdl_net 函数和诸如此类的东西很多,所以没有必要将它们全部倾倒在这里。

无论如何,我希望有人对帧率有一个聪明的提示,无论是如何提高它,一个不同的循环定时器功能,或者只是告诉我在 fps 上有一点损失是正常的 :)

【问题讨论】:

    标签: c++ sdl game-engine frame-rate game-loop


    【解决方案1】:

    我认为你的功能有错误

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

    【讨论】:

    • 这实际上发送的 fps 高于想要的 fps :P 在 200 上它达到了 270。可能是平均 fps 背后的数学错误,但我会仔细看看。不过谢谢:)
    猜你喜欢
    • 2011-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-10
    • 2012-07-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多