Pong-5 allows for the ball to bounce off the paddles and window boundaries. Open up Pong-5 to take a look at how we’ve incorporated AABB Collision Detection into our Pong program.
AABB Collision Detection
- AABB Collision Detection relies on all colliding entities to have “axis-aligned bounding boxes”, which simply means their collision boxes contain no rotation in our world space.
- To test two boxes, compare their left, right, top, and bottom edges. A collision happens only when the boxes overlap on both the horizontal axis and the vertical axis.
- The exact boolean expression is left for you to write in the challenge.
- We can use AABB Collision Detection to detect whether our ball is colliding with our paddles and react accordingly.
- We can apply similar logic to detect if the ball collides with a window boundary.
Important Code
Notice how we’ve added a didCollide() function to our Ball class. It should use the edge-overlap idea above to determine whether there has been a collision, returning true if so and false otherwise.
We can use this function in Ball::update() to keep track of the ball’s changing position and velocity after each collision with a paddle:
if (this.didCollide(player1) || this.didCollide(player2)) { this.dx = -this.dx * 1.03;
if (this.dy < 0) { this.dy = generateRandomNegativeNumber(400, 800); } else { this.dy = generateRandomPositiveNumber(400, 800); }}We also implement similar logic for collisions with the window edges:
if (this.y <= 0) { this.y = 0; this.dy = -this.dy;}
if (this.y >= this.canvasHeight - this.height) { this.y = this.canvasHeight - this.height; this.dy = -this.dy;}🧩 Challenge: Implement AABB collision
Complete Ball.didCollide() so it returns true when the ball and paddle rectangles overlap.
Files
Preparing Environment
- Installing dependencies
- Starting Vite dev server