Circle-Rectangle collision detection (intersection)

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

    Here is the modfied code 100% working:

    public static bool IsIntersected(PointF circle, float radius, RectangleF rectangle)
    {
        var rectangleCenter = new PointF((rectangle.X +  rectangle.Width / 2),
                                         (rectangle.Y + rectangle.Height / 2));
    
        var w = rectangle.Width  / 2;
        var h = rectangle.Height / 2;
    
        var dx = Math.Abs(circle.X - rectangleCenter.X);
        var dy = Math.Abs(circle.Y - rectangleCenter.Y);
    
        if (dx > (radius + w) || dy > (radius + h)) return false;
    
        var circleDistance = new PointF
                                 {
                                     X = Math.Abs(circle.X - rectangle.X - w),
                                     Y = Math.Abs(circle.Y - rectangle.Y - h)
                                 };
    
        if (circleDistance.X <= (w))
        {
            return true;
        }
    
        if (circleDistance.Y <= (h))
        {
            return true;
        }
    
        var cornerDistanceSq = Math.Pow(circleDistance.X - w, 2) + 
                                        Math.Pow(circleDistance.Y - h, 2);
    
        return (cornerDistanceSq <= (Math.Pow(radius, 2)));
    }
    

    Bassam Alugili

提交回复
热议问题