Pong

Pong is a smaller C++ project I used to practice game logic. It uses raylib for graphics and input and SFML for audio. The player controls one paddle and plays against a computer-controlled opponent.

Built with
C++, raylib for graphics and input, SFML for audio
Focus
Input, collisions, scoring, computer-controlled play

Putting the rules together

The project brought together several small systems: moving the paddles, detecting when the ball hits a paddle or wall, keeping score, and starting the next point. The computer-controlled paddle follows the ball, and the ball's direction changes after a point.

To detect a paddle hit, I find the point on the paddle closest to the ball. I use clamp to keep that point within the paddle's edges.

The clamp helper
// Keep a value within the given range.
float clamp(float value, float min, float max) {
if (value < min) return min;
if (value > max) return max;
return value;
}
Checking the ball against a paddle
// Find the point on the paddle closest to the ball.
float closestX = clamp(ballX, rectX, rectX + rectWidth);
float closestY = clamp(ballY, rectY, rectY + rectHeight);
float distanceX = ballX - closestX;
float distanceY = ballY - closestY;
return (distanceX * distanceX + distanceY * distanceY)
< (ballRadius * ballRadius);

If that point is closer to the ball's center than its radius, the ball overlaps the paddle. This is the check I use for both paddles.

What I learned

The rules were simple on their own. Putting them together meant checking what happened after a paddle hit, a missed ball, and the start of the next point.