1
$\begingroup$

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.

enter image description here

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.

$\endgroup$
  • $\begingroup$ 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. $\endgroup$ – Rahul Jan 16 '17 at 16:56
3
$\begingroup$

There is an intersection whenever the center of the circle lies in the green area.

enter image description here

You can detect this by checking if the center is inside the outer rectangle, but not in one of the corners at a distance larger than the radius.

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".

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.