Circle-Rectangle collision detection (intersection)

前端 未结 24 1381
无人共我
无人共我 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:17

    The simplest solution I've come up with is pretty straightforward.

    It works by finding the point in the rectangle closest to the circle, then comparing the distance.

    You can do all of this with a few operations, and even avoid the sqrt function.

    public boolean intersects(float cx, float cy, float radius, float left, float top, float right, float bottom)
    {
       float closestX = (cx < left ? left : (cx > right ? right : cx));
       float closestY = (cy < top ? top : (cy > bottom ? bottom : cy));
       float dx = closestX - cx;
       float dy = closestY - cy;
    
       return ( dx * dx + dy * dy ) <= radius * radius;
    }
    

    And that's it! The above solution assumes an origin in the upper left of the world with the x-axis pointing down.

    If you want a solution to handling collisions between a moving circle and rectangle, it's far more complicated and covered in another answer of mine.

提交回复
热议问题