Circle-Rectangle collision detection (intersection)

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

    This is the fastest solution:

    public static boolean intersect(Rectangle r, Circle c)
    {
        float cx = Math.abs(c.x - r.x - r.halfWidth);
        float xDist = r.halfWidth + c.radius;
        if (cx > xDist)
            return false;
        float cy = Math.abs(c.y - r.y - r.halfHeight);
        float yDist = r.halfHeight + c.radius;
        if (cy > yDist)
            return false;
        if (cx <= r.halfWidth || cy <= r.halfHeight)
            return true;
        float xCornerDist = cx - r.halfWidth;
        float yCornerDist = cy - r.halfHeight;
        float xCornerDistSq = xCornerDist * xCornerDist;
        float yCornerDistSq = yCornerDist * yCornerDist;
        float maxCornerDistSq = c.radius * c.radius;
        return xCornerDistSq + yCornerDistSq <= maxCornerDistSq;
    }
    

    Note the order of execution, and half the width/height is pre-computed. Also the squaring is done "manually" to save some clock cycles.

提交回复
热议问题