# Calculate if circle intersects a rectangle

In Euclidean 2D space I have a circle $A$ with radius $r$ and center $c(x_c,y_c)$, and a rectangle $B$ with height $h$, width $w$ which topleft corner is positioned at $d(x_d,y_d)$. The rectangle is not rotated, i.e. any vertex is parallel to either the $x$-axis or the $y$-axis. See the figure below for a simple sketch.

Given the values coordinates of $c$ and $d$ and the values of $r$, $h$ and $w$, how do I determine if the circle and the rectangle intersect, i.e. are overlapping? (The circle inside the rectangle without touching the borders of the rectangle, also counts as intersecting.

Background: I'm making a simple 2D game in which the player has to control two circles and has to avoid hitting blocks with this circles.

• The intersection occurs if the distance from $c$ to the closest point on or inside the rectangle is less than $r$. Said closest point is $({\rm clamp}(x_c,[x_d,x_d+w]), {\rm clamp}(y_c,[y_d-h,y_d]))$, qv. clamp. – Rahul Jan 16 '17 at 16:56

Concretely, assign a code from $0$ to $4$ to the abscissa of the center, depending on its position with respect to the four verticals (left to right). And similarly for the ordinate. The codes $0*,4*,*4,*4$ get a "no". The codes $11,13,31,33$ receive a "maybe" (need to check the distance to the corresponding corner). The other codes get a "yes".