Question

In a 2d space there are a rectangle and a circle that overlap each other. How can I calculate the smallest distance (depth) that I need to separate the circle and the rectangle?

Was it helpful?

Solution

I'll assume from the way you've described it if one shape entirely contains the other, that still counts as "overlapping"

The strategy to separate a circle from a rectangle while moving the circle the shortest distance is as follows:

  • Draw a line from the circle's centre to the nearest point on one of the rectangle's vertices
  • Pull the circle along this line until they are no longer overlapping

So to calculate the distance that it needs to be pulled, your formula will be:

pullDistance = radius - centreDistance

Where:

  • pullDistance is what you're trying to calculate
  • radius is the radius of the circle
  • centreDistance is the distance of the centre of the circle from the nearest point on the edge of the rectangle.

Two things to note:

  • If the centre of the circle is inside the rectangle, then centreDistance should be calculated the same way, but made negative
  • If the pullDistance is negative then the two shapes are already not overlapping, so the true distance is 0.

So since radius is known, all you have to do is calculate the centreDistance. The way to do this is to find the distance from the circle's centre point to each of the rectangle's four line segments and take the minimum. Finding the distance between a point and a line segment is a common task, I won't repeat how to do that here. This question has a lot of samples and information for how to do it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top