Math explaining time!
This all works around the Pythagorean theorem. The sum of the square of the lengths of the two shorter sides of a right triangle equals the square of the length of the third side. Written out, itâs a mouthful. Hereâs a picture.
Now, to actually find the distance of c, youâd need to take the square root of c; however, for the problem of two circles, determining the actual distance from the centers of the circles isnât needed to determine if they touch.
Letâs take our two circles and place them on the two points that make up side c.
We know the center of the circles, (x1, y1) and (x2, y2), as well as each circleâs radius, r1 and r2. From here you can see that the sum of the radii, r1 + r2, is identical to c. We also know the relationship between sides a and b with respect to c.
Since we know the center points of our two circles, we can calculate a and b in terms of our two circles and plug it back into Pythagorasâs theorem.
We can use this new equation to determine if the two circles are colliding or not without having to take the square root at all. The function would look identical to the solution @Copying provided above.
function circlesColide(center1:Point, r1:Number, center2:Point, r2:Number):Boolean
{
var x:Number = center2.x - center1.x;
var y:Number = center2.y - center1.y;
return (x*x + y*y) <= (r1*r1 + r2*r2);
}
A solution using square roots wouldnât be an incorrect solution to this problem; however, the reason this function is preferable is due to the way computers work. A computer is designed to add numbers really, really quick. Multiplication is just repeated addition, so they can multiply really quick as well.
Finding the square root of a number is a really complex and tricky algorithm that takes much longer than it would take to just add a bunch of stuff together; therefore, avoiding it will increase the execution speed of your program.
I hope this helps you understand all of this a bit better!