Detecting Collisions

Daniel Shiffman gives a good summary of this topic in Chapter 6 of The Nature of Code. As we are only dealing with balls (circles), we can say that any two balls are colliding if the distance between them is less than the sum of their radii.

Remember we are using a Vector as to represent the position of each ball. P5JS provides a method on the Vector class called dist which will measure the distance between two vectors. Using that, we can write this simple function:

function areColliding(ballA, ballB) {
  if (ballA.pos.dist(ballB.pos) < ballA.r + ballB.r) {
    return true
  }
  return false
}

Armed with this function, we can update our sketch to highlight when the balls are colliding. We change our draw() function to include a collision test between each pair of balls after all the balls have had their position updated. Something like this…

draw() {
...
  // Update the position of every ball
  for (let index = 0; index < balls.length; index++) {
    balls[index].update();
  }
  
  // Check for a collision between the balls
  var ballColor = "grey";
  if (areColliding(balls[0], balls[1])) {
    ballColor = "pink";
  }
  balls[0].color = ballColor;
  balls[1].color = ballColor;
...
}

We have added a new property to each Ball object called color (code not shown). In the draw() function we set the ball colour to grey, unless the balls are colliding in which case we set the colour to pink.