dj5 - 1 year ago 104
Java Question

# How to Determine if 2 Circles Overlap

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 distance = Math.sqrt((xDist*xDist) + (yDist*yDist));

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.

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();