Hello,
for the last few hours I've been trying to resolve a problem regarding the time management in my
SFML2 program. I want to make sure my program runs with the same speed on different computers.
I know there have been plenty of threads about this in the past but the problem is those either
use a function which is not available anymore (getframetime) or they don't go too much into
detail to clarify this matter for me.
#include <SFML/Audio.hpp>
#include <SFML/Graphics.hpp>
int main()
{
sf::VideoMode VMode(800, 600, 32);
sf::RenderWindow Window(VMode, "Empty Window");
sf::CircleShape circle;
circle.setRadius(8);
circle.setOutlineColor(sf::Color(0, 100, 100));
circle.setOutlineThickness(3);
circle.setPosition(10, 20);
circle.setFillColor(sf::Color(0, 255, 255));
sf::Clock clock;
clock.restart();
int updateNext = clock.getElapsedTime().asMilliseconds();
int cx, cy;
cx = 10;
cy = 20;
while (Window.isOpen())
{
sf::Event Event;
while (Window.pollEvent(Event))
{
switch (Event.type)
{
case sf::Event::Closed:
Window.close();
break;
default:
break;
}
}
Window.draw(circle);
Window.display();
Window.clear(sf::Color(0, 0, 0));
while (clock.getElapsedTime().asMilliseconds() > updateNext)
{
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
{
circle.setPosition(cx-=2, cy);
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
{
circle.setPosition(cx+=2, cy);
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
{
circle.setPosition(cx, cy-=1);
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
{
circle.setPosition(cx, cy+=1);
}
updateNext += 1/60;
}
}
return EXIT_SUCCESS;
}
I never really understood how these timing functions work.
I know you save the elapsed time since the program started but what time exactly is measured
by the start of each loop?
while (clock.getElapsedTime().asMilliseconds() > updateNext)
Shouldn't it be the time until the start of this loop (which would increase after every loop)?
I also don't quite get why this should help limiting the speed at which the loop is executed by
comparing it to the time since the program has started. And why do you add 1/60 to the elapsed
time since the program has started? I do know this is the desired framerate as 1/60 is equal to '60hz'
though.
Then again, the above code doesn't work anyway, so I'm not sure if my above assumptions are correct.
How do I make it work and how exactly does it work?
Thanks in advance,
CTryn