# Shortest distance between edges of a circle and a rectangle?

I have different kinds ob objects. An object can either be a rectangle or a circle. I want to calculate the shortest distance between the edges of each two objects.

For two circles it's just the distance between the two center points, minus radius1 and radius2.

For two rectangles I found this answer, and it works really well: Efficient minimum distance between two axis aligned squares?

But how can I calculate the minimum distance between the edges of a rectangle and a circle?

• Are your rectangles axis aligned? Jan 16, 2023 at 15:25
• Yes, they are axis aligned. Jan 16, 2023 at 15:31
• Then I suppose the shortest distance between a circle and a rectangle is the shortest distance between any of the 4 corners and the circle center, minus the radius, or the shortest distance between the x coordinate of the left/right edges and the x coordinate of the circle minus the radius, or the equivalent for the y axis. This may not be the optimal way to do this, but it could get you started. Jan 16, 2023 at 15:39
• I show an example of this in a previous answer — does that cover your needs? Jan 16, 2023 at 19:08
• Thanks to both of you! I found a solution for me. I used the things that @Vaillancourt suggested. Jan 17, 2023 at 12:03

I found a solution, that fits my needs:

If the centre of the circle is at right angles to one of the sides of the rectangle, the distance is simply the distance between the centre of the circle to that side minus the radius of the circle.

Otherwise, I take the nearest corner of the rectangle to the centre of the circle and calculate the distance using the Pythagorean theorem. Here you also have to subtract the radius of the circle.

Note: This code doesn't check if the circle is inside the rectangle, or vice versa.

function getDistanceCircleRect(circle, rectangle){

// x and y are the centre coordinates

xC = circle.x;
yC = circle.y;
r = circle.width/2;

xR = rectangle.x;
yR = rectangle.y;
wR = rectangle.width;
hR = rectangle.height;

topR = yR - hR/2;
bottomR = yR + hR/2;
leftR = xR - wR/2;
rightR = xR + wR/2;

if(yC >= topR && yC <= bottomR && ((xC+r) >= rightR || (xC-r) <= leftR)){

d1 = Math.abs(xC - rightR);
d2 = Math.abs(xC - leftR);

min_distance = Math.min(d1, d2) - r;
}
else if(xC >= leftR && xC <= rightR && ((yC+r) >= bottomR || (yC-r) <= topR)){

d1 = Math.abs(yC - topR);
d2 = Math.abs(yC - bottomR);

min_distance = Math.min(d1, d2) - r;
}
else{

nextX = Math.min(Math.abs(xC - leftR), Math.abs(xC - rightR));
nextY = Math.min(Math.abs(yC - topR), Math.abs(yC - bottomR));

min_distance = Math.sqrt((nextX)**2 + (nextY)**2) - r;
}

return min_distance;
}