Week 3 – OOP Assignment

Of course! Here is a well-structured response perfect for a class discussion board or homework submission. It’s written from your perspective, explains the concepts clearly, and highlights the collision code as you requested.

Hi everyone,

For this week’s work on OOP, I wanted to build on what we did last time implementing a bouncing ball with OOP. I wanted to make it kinds more interactive this time. I wanted to take a familiar p5.js example and make it more dynamic by implementing proper OOP principles, allowing the balls to not only bounce off the walls but also collide realistically with each other.

I created a `Ball` class that bundles together all the data (properties like `x`, `y`, `xspeed`, `radius`) and the functions (methods like `move()`, `display()`, `bounceWalls()`) that define what a ball is and what it can do. This makes the main `sketch.js` file much cleaner and more manageable. Instead of tracking dozens of separate variables for each ball, I can simply create an array of `Ball` objects and let each object manage its own state. And this what gave me the freedom of creating a lot of new balls whenever the mouse is clicked.

One of the most interesting parts of this project was implementing the collision detection between the balls. A simple approach where every ball checks against every other ball can lead to a glitch where they get stuck. When Ball A collides with Ball B, they reverse direction. But in the same frame, when Ball B checks against Ball A, it reverses direction *again*, undoing the bounce.

The highlight of my code is the solution to this problem in the main `draw()` loop. By using a nested loop where the inner loop starts at `j = i + 1`, I can ensure that every pair of balls is checked for collision exactly once per frame. This prevents the double-bounce glitch and is much more efficient.

Here is the snippet for the collision logic:

for (let i = 0; i < balls.length; i++) {
for (let j = i + 1; j < balls.length; j++) {
let ball1 = balls[i];
let ball2 = balls[j];
// Check the distance between the two balls
let distance = dist(ball1.x, ball1.y, ball2.x, ball2.y);
// If they overlap, trigger the collision resolution function
if (distance < ball1.radius + ball2.radius) {
resolveCollision(ball1, ball2);
}
}
}

Leave a Reply