Search code examples
c++frame-rategame-loop

gameloop framerate control issues


this is driving me mad, anyway, usual story, attempting to guarantee the same speed in my very simple game across any windows machine that runs it. im doing it by specifying a 1/60 value, then ensuring a fram cant run until that value has passed in time since the last time it was called. the problem im having is 1/60 equates to 30hz for some reason, I have to set it to 1/120 to get 60hz. its also not bang on 60hz, its a little faster.

if i paste it out here, could someone tell me if they see anything wrong? or a more precise way to do it maybe?

float controlFrameRate = 1./60 ;

while (gameIsRunning)
{
    frameTime += (system->getElapsedTime()-lastTime);
    lastTime = system->getElapsedTime();

    if(frameTime > controlFrameRate)
    {
        gameIsRunning = system->update();
        
        //do stuff with the game

        frameTime = .0f;                   
    }
} 

Solution

  • Don't call getElapsedTime twice, there may be a slight difference between the two calls. Instead, store its value, then reuse it. Also, instead of setting the frameTime to 0, subtract controlFrameRate from it, that way, if one frame takes a little longer, the next one will make up for it by being a little shorter.

    while (gameIsRunning)
    {
        float elapsedTime = system->getElapsedTime();
    
        frameTime += (elapsedTime-lastTime);
        lastTime = elapsedTime;
    
        if(frameTime > controlFrameRate)
        {
            gameIsRunning = system->update();
    
            //do stuff with the game
    
            frameTime -= controlFrameRate;
        }
    }
    

    I'm not sure about your problem with having to set the rate to 1/120, what timing API are you using here?