Build Breakout using C++ and SFML

Lesson 3 of 7

The Paddle

Wrap the paddle's shape, position, and behavior into a class, this keeps every piece of paddle logic in one place instead of scattered loose variables.

class Paddle {
public:
    Paddle(float x, float y) {
        shape.setSize(sf::Vector2f(100.f, 15.f));
        shape.setFillColor(sf::Color::White);
        shape.setPosition(x, y);
    }

    void update(float deltaTime, float windowWidth) {
        float dx = 0.f;
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) {
            dx = -speed * deltaTime;
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) {
            dx = speed * deltaTime;
        }

        shape.move(dx, 0.f);

        // Clamp to the window so the paddle can't slide off-screen
        sf::Vector2f pos = shape.getPosition();
        float width = shape.getSize().x;
        if (pos.x < 0.f) shape.setPosition(0.f, pos.y);
        if (pos.x + width > windowWidth) shape.setPosition(windowWidth - width, pos.y);
    }

    void draw(sf::RenderWindow& window) {
        window.draw(shape);
    }

    sf::RectangleShape shape;

private:
    float speed = 400.f;
};

The pieces

  • sf::Keyboard::isKeyPressed(...) checks the current state of a key, unlike sf::Event, it doesn't wait for a press event, which is exactly what you want for smooth, continuous movement.
  • Clamping reads the paddle's current position and size, then snaps it back inside [0, windowWidth] if it would otherwise cross an edge.
  • void draw(sf::RenderWindow& window) takes the window by reference, so the class can draw itself without copying the whole window object.

TIP

Passing sf::RenderWindow& (a reference) instead of sf::RenderWindow (a copy) matters here, sf::RenderWindow isn't copyable at all, and even if it were, copying an entire window every frame would be wasteful.

📝 Paddle Quiz

Passing score: 70%
  1. 1.Why use sf::Keyboard::isKeyPressed() instead of sf::Event for paddle movement?

  2. 2.Clamping the paddle position prevents it from moving off the edges of the window.