2012-04-14 62 views
1

我们正在为我们的C++类制作一个游戏引擎,除了我们在FPS方面有一些小问题之外,我们主要完成了一切。它总是比我们设定的速度慢10-20%左右,而且我们想知道这是由于错误/糟糕的代码还是它的原因?如果我们将它设置为500+,它的上限为350,但这主要是由于计算机无法处理更多。如果我们将它设置为50,我们会在40-44左右。SDL - C++中LoopTimer的FPS问题

下面是来自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); 
    } 
} 

更新基本上是被称为在我们的run方法游戏管理:

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

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

    _Update(); 
    _Draw(); 

    _timer.SleepUntilNextFrame(); 
    }  
    return 0; 
} 

如果需要,我可以提供更多的代码,或者我很乐意将代码发给任何可能需要它的人。包括sdl_net函数在内的很多事情都是如此,所以没有必要把它全部扔到这里。

无论如何,我希望有人有关于帧率一个聪明的小费,无论是如何改进它,不同的looptimer功能或只是告诉我,这是正常的在FPS :)

回答

0

小的损失,我认为有在fonction错误

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

这实际上比想要的FPS发送的FPS越高:P上200就跑到270可能是与平均FPS背后的数学一个错误,但我得仔细看看。虽然谢谢:) – 2012-04-24 07:43:17