Build Breakout using C++ and SFML

Lesson 2 of 7

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 clock starts 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 * deltaTime means "how far should this move, given it travels at speed pixels per second and this frame took deltaTime seconds", this keeps motion smooth and consistent regardless of framerate.
  • window.draw(shape) queues the shape to be drawn, it isn't actually shown until window.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.

📝 Game Loop Quiz

Passing score: 70%
  1. 1.Why should movement be multiplied by deltaTime instead of using a fixed step per frame?

  2. 2.The SFML class used as a stopwatch to measure elapsed time between frames is sf::____.

  3. 3.window.draw() immediately shows the shape on screen, before window.display() is called.