1
votes

I have a question pertaining writing a java program and in part of the program it checks if the circles overlap or intersect at any point and displays if they do.

I believe the formula to do this is (r1+r2)^2 <= (x2-x1)^2+(y2-y1)^2

After applying this formula to my code it is not able to detect if overlapping or intersecting.

    //variables
    //crOneRadius = radius of circle 1
    //crTwoRadius = radius of circle 2
    //crOneCenterX = x axis location of circle 1
    //crOneCenterX = y axis location of circle 1
    //crTwoCenterX = x axis location of circle 2
    //crTwoCenterX = y axis location of circle 2     
    //BOoverlap = is boolean if it is ovelapping circles set to true
    if((crOneRadius+crTwoRadius)*(crOneRadius+crTwoRadius)<=((crTwoCenterX-crOneCenterX)*(crTwoCenterX-crOneCenterX))+((crTwoCenterY-crOneCenterY)*(crTwoCenterY-crOneCenterY)))
        BOoverlap=true;//overlap is true
1
How do you know it's not working? I assume (though it's not in your code in your question) that you initialize BOverlap (BTW, you should not capitalize the first letter of a variable in Java) to false. Have you observed cases where it's true and should be false, or where it's false and should be true?aro_tech
Yes I have observed this It come out false everytime, I'm using java fx to display the two circles and it never is trueike
Have you logged/printed the values of the 6 variables and the BOverlap result? I suggest you isolate this calculation in its own method and test it with different values (you can write a test in a main() method if you don' t want to use JUnit or TestNG).aro_tech
BTW, to better see what's going on in the code, I'd also calculate some intermediate values, so the calculation looks more like sumOfRadii*sumOfRadii <= deltaX*deltaX + deltaY*deltaY. To improve readablity even more, you might even want to write your own square() method or use Math.pow(x,2), giving something like square(sumOfRadii) <= square(deltaX) + square(deltaY).aro_tech

1 Answers

1
votes

The distance d between the two centers C1 and C2 must be smaller that the sum of their radii r1 + r2 for the circles to intercept:

enter image description here

|C1 - C2| <= r1 + r2

Squaring both sides

(x1 - x2)ˆ2 + (y1 - y2)^2 <= (r1 + r2)^2

or

(r1 + r2)^2 >= (x1 - x2)^2 + (y1 - y2)^2,

which is the opposite condition to the one you are using.