dj5 - 9 months ago 54

Java Question

So I'm creating a class and have to determine if two circles are overlapping based on their distance. This is what I have:

`Circle a = other;`

Circle b = other;

double xDist = a.getX() - a.getX();

double yDist = b.getY() - b.getY();

double radi = a.getRadius() + b.getRadius();

double distance = Math.sqrt((xDist*xDist) + (yDist*yDist));

if((distance < radi * radi)) {

return true;

} else {

return false;

}

My process is that if the distance of the centers is less than the sum of their radii, then the circles overlap.

Answer

Your error is that you're trying to compare the distance with the *square* of the sum of the radii. You want to compare the distance with the sum of the radii.

Alternatively, you could compare the *square* of the distance to the *square* of the sum of the radii, which would remove the need to use `Math.sqrt`

.

Note also that there's no point in having variables `a`

and `b`

, when you've already got `this`

and `other`

to refer to the two discs. In fact, you've incorrectly made `a`

and `b`

both refer to `other`

. You could fix this as follows.

```
public boolean overlaps(Disk other) {
double xDistance = getX() - other.getX();
double yDistance = getY() - other.getY();
double sumOfRadii = getRadius() + other.getRadius();
double distanceSquared = xDistance * xDistance + yDistance * yDistance;
boolean isOverlapping = distanceSquared < sumOfRadii * sumOfRadii;
return isOverlapping;
}
```

Source (Stackoverflow)