Build Breakout using C++ and SFML

Lesson 4 of 7

The Ball

The ball needs a position, a shape, and a velocity, how fast and in what direction it's moving on each axis.

class Ball {
public:
    Ball(float x, float y) {
        shape.setRadius(10.f);
        shape.setFillColor(sf::Color::Red);
        shape.setPosition(x, y);
    }

    void update(float deltaTime, float windowWidth) {
        shape.move(velocity.x * deltaTime, velocity.y * deltaTime);

        sf::Vector2f pos = shape.getPosition();
        float radius = shape.getRadius();

        // Bounce off the left and right walls
        if (pos.x <= 0.f || pos.x + radius * 2 >= windowWidth) {
            velocity.x = -velocity.x;
        }

        // Bounce off the ceiling
        if (pos.y <= 0.f) {
            velocity.y = -velocity.y;
        }
    }

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

    sf::CircleShape shape;
    sf::Vector2f velocity = sf::Vector2f(200.f, -200.f);
};

The pieces

  • sf::Vector2f velocity stores an (x, y) pair of floats, positive x moves right, negative moves left, positive y moves down (SFML's y-axis grows downward, unlike math class), negative moves up.
  • Bouncing is just flipping the sign of the relevant component, hit a side wall, invert velocity.x, hit the ceiling, invert velocity.y.
  • Notice there's no floor bounce yet, when the ball passes below the paddle, that's a "miss", handled in the Score and Lives lesson, not treated like a wall.

TIP

shape.getPosition() on an sf::CircleShape returns the top-left corner of its bounding box, not the center, that's why the right-wall check adds radius * 2 (the shape's full width) instead of just radius.

📝 Ball Quiz

Passing score: 70%
  1. 1.To make the ball bounce off a wall, you flip the sign of its ____.x or .y velocity component.

  2. 2.In SFML's coordinate system, which direction does increasing y move a shape?