The Game Loop
Every real-time game runs the same three steps, over and over, dozens of times per second: handle input, update the world, draw the world.
Framerate and deltaTime
If you move an object by a fixed amount every frame, the game runs faster on powerful computers and slower on weak ones, because faster computers simply produce more frames per second. The fix is deltaTime: the actual time elapsed since the last frame, used to scale every movement.
#include <SFML/Graphics.hpp>
int main() {
sf::RenderWindow window(sf::VideoMode(800, 600), "Breakout");
window.setFramerateLimit(60);
sf::CircleShape shape(20.f);
shape.setFillColor(sf::Color::Green);
float speed = 200.f; // pixels per second
sf::Clock clock;
while (window.isOpen()) {
float deltaTime = clock.restart().asSeconds();
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed) {
window.close();
}
}
shape.move(speed * deltaTime, 0.f);
window.clear(sf::Color::Black);
window.draw(shape);
window.display();
}
return 0;
}
The pieces
window.setFramerateLimit(60)caps the loop at roughly 60 frames per second, so it doesn't burn 100% CPU rendering thousands of frames nobody sees.sf::Clock clockstarts a stopwatch.clock.restart()returns the elapsed time since the last restart and resets it, so calling it once per frame gives you exactly that frame's duration.speed * deltaTimemeans "how far should this move, given it travels atspeedpixels per second and this frame tookdeltaTimeseconds", this keeps motion smooth and consistent regardless of framerate.window.draw(shape)queues the shape to be drawn, it isn't actually shown untilwindow.display().
WARNING
Moving objects by a flat number of pixels per frame (instead of speed * deltaTime) is a classic bug, the game will play at wildly different speeds on different hardware.