Problem trying to lock framerate at 60 FPS

Posted by shad0w on Game Development See other posts from Game Development or by shad0w
Published on 2012-04-14T10:37:18Z Indexed on 2012/04/14 11:46 UTC
Read the original article Hit count: 237

Filed under:
|
|

I've written a simple class to limit the framerate of my current project. But it does not work as it should. Here is the code:

void FpsCounter::Process()
{
deltaTime = static_cast<double>(frameTimer.GetMsecs());
waitTime = 1000.0/fpsLimit - deltaTime;
frameTimer.Reset();

if(waitTime <= 0)
{
    std::cout << "error, waittime: " << waitTime << std::endl;
}
else
{
    SDL_Delay(static_cast<Uint32>(waitTime));
}

if(deltaTime == 0)
{
    currFps = -1;
}
else
{
    currFps = 1000/deltaTime;
}

std::cout << "--Timings--" << std::endl;
std::cout << "Delta: \t" << deltaTime << std::endl;
std::cout << "Delay: \t" << waitTime << std::endl;
std::cout << "FPS: \t" << currFps << std::endl;
std::cout << "--       --" << std::endl;
}

Timer::Timer()
{
startMsecs = 0;
}

Timer::~Timer()
{
// TODO Auto-generated destructor stub
}

void Timer::Start()
{
started = true;
paused = false;
Reset();
}

void Timer::Pause()
{
if(started && !paused)
{
    paused = true;

    pausedMsecs = SDL_GetTicks() - startMsecs;
}
}

void Timer::Resume()
{
if(paused)
{
    paused = false;

    startMsecs = SDL_GetTicks() - pausedMsecs;

    pausedMsecs = 0;
}
}

int Timer::GetMsecs()
{
if(started)
{
    if(paused)
    {
        return pausedMsecs;
    }
    else
    {
        return SDL_GetTicks() - startMsecs;
    }
}
return 0;
}

void Timer::Reset()
{
startMsecs = SDL_GetTicks();
}

The "FpsCounter::Process()" Method is called everytime at the end of my gameloop.

I've got the problem that the loop is correctly delayed only every second frame, so it runs one frame delayed at 60 FPS and the next without delay at over 1000 fps.

I am searching the error quite a while now, but I do not find it.

I hope somebody can point me in the right direction.

© Game Development or respective owner

Related posts about c++

Related posts about sdl