0

I'm trying to limit my gameloop fps using SFML but it's not working correctly.

if I divide 60/1000 shouldn't the result be the time of each frame to get 60 FPS?

I put in 60 but I only get 33 does anyone know where I made a mistake?

Here is my header

class Game 
{
    //..
    sf::Clock deltaTimeClock;
    float deltaTime;

    const float frameTime = 60.0f/ 1000.0f;

    bool aSecondPassed();
    float currentFPS = 0;
    sf::Clock second;

//..
}

My implementation


    //...
    
    void Game::updateDeltaTime()
    {
        this->deltaTime = (this->deltaTimeClock.restart().asSeconds());
    
    }
    
    //...
    
    void Game::run()
    {
        while (this->window->isOpen())
        {
        this->showFPS();
        this->tick();
        this->render();
            
        while (deltaTime < this->frameTime)
        {
            this->deltaTime = this->deltaTimeClock.getElapsedTime().asSeconds();
    
        }
    
        this->updateDeltaTime();
    }
}

  • 1
    In a typical timing loop, you don't just zero the clock. By doing that, you lose any information you previously had about how much your timing loop overshot the target frame time. A more robust way to do it is to divide the frame time into the elapsed time and keep the remainder as your "reset" elapsed time. For example, if I render a frame in 0.3 of a time slice, then sleep for 0.9 before triggering the next frame, I have 0.2 units of elapsed time that I might want to make up for in the next frame. If I were to zero the clock, my frame rate drifts by 0.2 frames. – paddy Apr 13 '23 at 04:08
  • 1
    60 FPS is 1/60th of a second per frame. Your `frameTime` is 60 milliseconds, which is not the same thing. (Also, stick to `Time`, don't convert it to a `float`; it has all the operations you need for working with time, without messing with conversions. `const Time frameTime = seconds(1.0f/60.0f);`) – molbdnilo Apr 13 '23 at 04:23
  • 4
    Start with [Gaffer on Games - Fix Your Timestep!](https://gafferongames.com/post/fix_your_timestep/) and then see the rest of [Gaffer on Games (most game articles at bottom)](https://gafferongames.com/), e.g. Integration Basics, Spring Physics and Physics in 3D, etc... – David C. Rankin Apr 13 '23 at 05:01
  • @molbdnilo That worked didn't know you could use Time here and 1/60 worked too thanks! – David Rocha Apr 13 '23 at 22:16
  • @DavidC.Rankin Thanks for the tip I'll take a look and see if I can improve my loop. – David Rocha Apr 13 '23 at 22:18

1 Answers1

0

Getting a stable 60 fps by updating the loop condition to

this->deltaTimeClock.getElapsedTime().asSeconds() < this->frameTime

But I will study more on the subject, maybe there is a better way to implement this. Thank you all for your help.