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 velocitystores an (x, y) pair of floats, positivexmoves right, negative moves left, positiveymoves 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, invertvelocity.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.