In this post we’re going to start work on a pool game. Pool is quite a nice example for a game, because really it’s a two-dimensional game. The balls are always (trick shots aside!) on the table, so you can create the game as a 2D game viewed from above.

One of the key aspects of implementing a pool game is to detect when the balls collide with each other and make them bounce accordingly. When viewed in 2D, from above, the balls are simply circles. So in this post we’ll look at how to detect when two circles collide with each other.

## The Shortest Path

Detecting whether circles collide is quite simple, but makes use of a crucial observation: if two circles collide at all, then they will collide along the line between their two centres.

To help you understand this, I’ve put together a little Greenfoot scenario. There are two circles, one stationary and one that you move around with the mouse. A line is drawn between their two centres. Move them around, and notice that you can’t make the circles touch without them overlapping along the line between the two centres.

So then, let’s consider that line between the two centres of two circles, which (as ever) can be viewed as the hypotenuse of a right-angled triangle formed by the X and Y axes:

We can work out the total length of the line between the centres using Pythagoras: we just calculate the X distance and Y distance between the centres using subtraction, then Pythagoras gives us the distance. So once we have the distance, how do we work out if the circles overlap? Well, we just need a little logic: if the distance between the two centres is smaller than the sum of the radiuses, the circles must be overlapping — as above. If, on the other hand, the distance is greater than the sum of the radiuses, the circles can’t be overlapping — as below:

(If the distance equals the sum, the circles are only just touching: whether you count this as a collision is a matter of preference).

The earlier scenario displays all the numbers I’ve been referring to, in the top right, so you can have a play if you want, over on the Greenfoot site. Next time we’ll start working on the actual pool scenario.

Comments on:"Pooled Knowledge" (1)Making Your Balls Bounce « The Sinepostsaid:[…] this post, we will finally complete our pool game. We’ve already seen how to detect collisions between balls: we just need to check if two circles are overlapping. We’ve also seen how to resolve a […]