Pong

Pong is a smaller C++ game I built with raylib for graphics and input, and SFML for audio. You control one paddle against a computer-controlled opponent.

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

How a point works

The computer paddle follows the ball. A paddle hit sends the ball back; a miss updates the score and starts the next point. Building those parts meant checking what should happen in sequence, especially when a collision and a score change happen close together.

Detecting a paddle hit

The ball is a circle and the paddle is a rectangle. To check whether they overlap, I find the point on the paddle closest to the ball's centre. clamp keeps that point inside 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 the distance from that point to the ball's centre is less than the ball's radius, it's a hit. I use the same check for both paddles.