How can I tell whether a circle and a rectangle intersect in 2D Euclidean space? (i.e. classic 2D geometry)
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
There are only two cases when the circle intersects with the rectangle:
Note that this does not require the rectangle to be axis-parallel.
(One way to see this: if none of the edges has a point in the circle (if all the edges are completely ‘outside’ the circle), then the only way the circle can still intersect the polygon is if it lies completely inside the polygon.)
With that insight, something like the following will work, where the circle has centre
Pand radiusR, and the rectangle has verticesA,B,C,Din that order (not complete code):If you’re writing any geometry you probably have the above functions in your library already. Otherwise,
pointInRectangle()can be implemented in several ways; any of the general point in polygon methods will work, but for a rectangle you can just check whether this works:And
intersectCircle()is easy to implement too: one way would be to check if the foot of the perpendicular fromPto the line is close enough and between the endpoints, and check the endpoints otherwise.The cool thing is that the same idea works not just for rectangles but for the intersection of a circle with any simple polygon — doesn’t even have to be convex!