after visiting http://gameprogrammingpatterns.com/game-loop.html a friend of mine and I decided to develop a little game using the fixed time step algorithm and SFML2.
So far we have
- {l Code}: {l Select All Code}
while(window.isOpen()) {
sf::Time currentT = clock.getElapsedTime();
sf::Time elapsedT = currentT - previousT;
previousT = currentT;
lag += elapsedT;
// todo: validate input here
while(lag >= msPerUpdate) {
update();
lag -= msPerUpdate;
}
draw( lag.asSeconds() / msPerUpdate.asSeconds() );
}
with
- {l Code}: {l Select All Code}
sf::Time msPerUpdate = sf::seconds(0.0166);
because 1000 ms / 60 fps ~= 16,6667 ms and that seems to work. At least the sprites have fluid movement.
The problem is the high CPU usage.
Is there a possibility to put in an sf::sleep() somewhere?
Simply putting it behind causes stuttering and doing something like this
- {l Code}: {l Select All Code}
while(lag >= msPerUpdate) {
update();
sf::sleep(sf::milliseconds(2));
lag -= msPerUpdate + sf::milliseconds(2);
}
only gets 1/2 of the CPU usage, which is still too much, considering the simplicity of the game code.
Edit: Another question is: Is this kind of loop even suitable for low CPU usage?
Thank you in advance.