Circle-Rectangle collision detection (intersection)

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

    Improving a little bit the answer of e.James:

    double dx = abs(circle.x - rect.x) - rect.w / 2,
           dy = abs(circle.y - rect.y) - rect.h / 2;
    
    if (dx > circle.r || dy > circle.r) { return false; }
    if (dx <= 0 || dy <= 0) { return true; }
    
    return (dx * dx + dy * dy <= circle.r * circle.r);
    

    This subtracts rect.w / 2 and rect.h / 2 once instead of up to three times.

提交回复
热议问题