SFML community forums

Help => System => Topic started by: hoenchioma on September 10, 2018, 02:50:59 pm

Title: Clock::getElapsedTime() with asMilliseconds() causing weird behaviour
Post by: hoenchioma on September 10, 2018, 02:50:59 pm
When using the Clock::getElapsedTime() or restart() I noticed something weird.

        RenderWindow window(VideoMode(700, 700), "Hello SFML");
        Event event;
        Clock clock;
        Clock clock2;
        Clock c3;
       
        RectangleShape box(Vector2f(20, 20));

        //window.setFramerateLimit(30);

        while (window.isOpen())
        {      
                while (window.pollEvent(event))
                {
                        if (event.type == Event::EventType::Closed)
                        {
                                window.close();
                        }
                }
                box.move(0, 0.5 * clock.restart().asMilliseconds());
                clock.restart();

                if (box.getPosition().y > 700)
                {
                        cerr << clock2.getElapsedTime().asSeconds() << endl;
                        window.close();
                }

                window.clear();

                window.draw(box);

                window.display();
        }
 

The code seems simple enough it outputs how much the box takes to move across the screen. Moving a box to down. I was trying to implement frame rate independent movement. This produces weird jagged movement. And the measured time varying at each run (3-6 seconds). So I decided to measure the elapsed time to see whats going on.
        box.move(0, 0.5 * clock.getElapsedTime().asMilliseconds());
        cerr << clock.restart().asMilliseconds() << endl;
 
Suddenly the movement was fixed and the time taken seemed to average to around 1.76 seconds.
This was so at any framerate I set (as it should be). But as soon as i commented out the second line the same happened again.
What's even more weird is that this doesn't seem to happen when I use asMicroseconds().
Is this me or what could be causing this. I'm running this on a Windows 10 64 bit machine (developing for 32 bit machines) if that helps.
Title: Re: Clock::getElapsedTime() with asMilliseconds() causing weird behaviour
Post by: eXpl0it3r on September 10, 2018, 03:46:34 pm
If you have a a very high framerate, then asMilliseconds will return 0 due to rounding errors, thus you may end up with odd movement. Introducing a std::cerr adds more time to each frame, making asMilliseconds return useful values.

I suggest using asSeconds which provides you a float and won't be 0, even for very short frame time.
Additionally, you should really setFramerateLimit your FPS, as you're burning CPU and GPU time for nothing. ;)
Title: Re: Clock::getElapsedTime() with asMilliseconds() causing weird behaviour
Post by: hoenchioma on October 24, 2018, 06:09:55 am
Thanks a lot. That seemed to solve the problem.  ;D