I'm looking for an algorithm to detect if a circle intersects with any other circle in the same plane (given that there can be more than one circle in a plane).
One method I have found is to do the separating axis test. It says:
Two objects don't intersect if you can find a line that separates the two objects, i.e. a line such that all objects or points of an object are on different sides of the line.
However, I don't know how to apply this method to my case.
Can anybody help me?
This solution in Java used the mathematical expresion which was described above:
If the distance between the centers of two circles is at most the sum of their radii, but at least the absolute value of the difference between the radii, then the circles themselves intersect at some point.
The "at least the difference" part applies if you care only about the circles themselves, and not their inner areas. If you care whether the circles or the areas they enclose share any points -- that is, if one circle totally inside the other counts as "intersecting" to you -- then you can drop the "at least the difference" check.
Swift 4 solution:
Two circles intersect if, and only if, the distance between their centers is between the sum and the difference of their radii. Given two circles
(x0, y0, R0)
and(x1, y1, R1)
, the formula is as follows:Squaring both sides lets you avoid the slow
SQRT
, and stay with ints if your inputs are integers:Since you need only a yes/no test, this check is faster than calculating the exact intersection points.
The above solution should work even for the "one circle inside the other" case.
Assuming filled circle intersection (ie: One circle inside another is an intersection).
Where:
Code:
I tried the formula given here that is a supposed answer and everyone voted way up although it's seriously flawed. I wrote a program in JavaFX to allow the user to test whether two circles intersect by changing each circles centerX, centerY, and Radius values and this formula absolutely does not work except one way...I can't figure out why but when I move circle 2 near circle 1 it works but when I move circle 1 to the other side near circle 2 it doesn't work.....????? that's a bit odd...figured the formula needed to be tested the opposite way as well so tried that and it doesn't work
This works:
Go here for the formula Intersection of two circles
The formula used is not my formula all credit goes to Paul Bourke(April 1997)