TerrainDisplay.Collision.Intersection.IntersectSegmentRectangle2D C# (CSharp) Method

IntersectSegmentRectangle2D() public static method

public static IntersectSegmentRectangle2D ( System.Vector2 rectMin, System.Vector2 rectMax, System.Vector2 point1, System.Vector2 point2 ) : bool
rectMin System.Vector2
rectMax System.Vector2
point1 System.Vector2
point2 System.Vector2
return bool
        public static bool IntersectSegmentRectangle2D(Vector2 rectMin, Vector2 rectMax, Vector2 point1, Vector2 point2)
        {
            // Find min and max X for the segment
            var a_rectangleMinX = rectMin.X;
            var a_rectangleMinY = rectMin.Y;
            var a_rectangleMaxX = rectMax.X;
            var a_rectangleMaxY = rectMax.Y;
            var a_p1x = point1.X;
            var a_p1y = point1.Y;
            var a_p2x = point2.X;
            var a_p2y = point2.Y;

            var minX = a_p1x;
            var maxX = a_p2x;
            if (a_p1x > a_p2x)
            {
                minX = a_p2x;
                maxX = a_p1x;
            }

            // Find the intersection of the segment's and rectangle's x-projections
            if (maxX > a_rectangleMaxX)
            {
                maxX = a_rectangleMaxX;
            }

            if (minX < a_rectangleMinX)
            {
                minX = a_rectangleMinX;
            }

            if (minX > maxX) // If their projections do not intersect return false
            {
                return false;
            }

            // Find corresponding min and max Y for min and max X we found before

            var minY = a_p1y;
            var maxY = a_p2y;

            var dx = a_p2x - a_p1x;

            if (Math.Abs(dx) > Epsilon)
            {
                var a = (a_p2y - a_p1y)/dx;
                var b = a_p1y - a*a_p1x;
                minY = a*minX + b;
                maxY = a*maxX + b;
            }

            if (minY > maxY)
            {
                var tmp = maxY;
                maxY = minY;
                minY = tmp;
            }

            // Find the intersection of the segment's and rectangle's y-projections
            if (maxY > a_rectangleMaxY)
            {
                maxY = a_rectangleMaxY;
            }

            if (minY < a_rectangleMinY)
            {
                minY = a_rectangleMinY;
            }

            return (minY <= maxY);
        }