Circle-Rectangle collision detection (intersection)

前端 未结 24 1881
无人共我
无人共我 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's a fast one-line test for this:

    if (length(max(abs(center - rect_mid) - rect_halves, 0)) <= radius ) {
      // They intersect.
    }
    

    This is the axis-aligned case where rect_halves is a positive vector pointing from the rectangle middle to a corner. The expression inside length() is a delta vector from center to a closest point in the rectangle. This works in any dimension.

提交回复
热议问题