Circle-Rectangle collision detection (intersection)

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

    • First check if the rectangle and the square tangent to the circle overlaps (easy). If they do not overlaps, they do not collide.
    • Check if the circle's center is inside the rectangle (easy). If it's inside, they collide.
    • Calculate the minimum squared distance from the rectangle sides to the circle's center (little hard). If it's lower that the squared radius, then they collide, else they don't.

    It's efficient, because:

    • First it checks the most common scenario with a cheap algorithm and when it's sure they do not collide, it ends.
    • Then it checks the next most common scenario with a cheap algorithm (do not calculate square root, use the squared values) and when it's sure they collide it ends.
    • Then it executes the more expensive algorithm to check collision with the rectangle borders.

提交回复
热议问题