Circle-Rectangle collision detection (intersection)

前端 未结 24 1684
无人共我
无人共我 2020-11-22 02:55

How can I tell whether a circle and a rectangle intersect in 2D Euclidean space? (i.e. classic 2D geometry)

24条回答
  •  一整个雨季
    2020-11-22 03:01

    Here is another solution that's pretty simple to implement (and pretty fast, too). It will catch all intersections, including when the sphere has fully entered the rectangle.

    // clamp(value, min, max) - limits value to the range min..max
    
    // Find the closest point to the circle within the rectangle
    float closestX = clamp(circle.X, rectangle.Left, rectangle.Right);
    float closestY = clamp(circle.Y, rectangle.Top, rectangle.Bottom);
    
    // Calculate the distance between the circle's center and this closest point
    float distanceX = circle.X - closestX;
    float distanceY = circle.Y - closestY;
    
    // If the distance is less than the circle's radius, an intersection occurs
    float distanceSquared = (distanceX * distanceX) + (distanceY * distanceY);
    return distanceSquared < (circle.Radius * circle.Radius);
    

    With any decent math library, that can be shortened to 3 or 4 lines.

提交回复
热议问题