public bool IntersectsWith(Line other) { if (this == other) { return(true); } double mx = X2 - X1; double my = Y2 - Y1; double rmx = other.X2 - other.X1; double rmy = other.Y2 - other.Y1; double dx = other.X1 - X1; double dy = Y1 - other.Y1; double d = (mx * rmy - my * rmx); double n = (mx * dy + my * dx) / d; double q = (rmx * dy + rmy * dx) / d; if (n > 0 && n < 1 && q > 0 && q < 1) { return(true); } //if (other.X1 == 0 && other.Y1 == 0 && other.X2 == 1 && other.Y2 == 0 && X1 == 3 && Y1 == 0 && X2 == 0 && Y2 == 0) // System.Diagnostics.Debugger.Break(); // check if they have the same gradient if ((Y2 - Y1) * (other.X2 - other.X1) != (other.Y2 - other.Y1) * (X2 - X1)) { return(false); } // check if (X1, Y1) lies on the other line if ((other.Y1 - Y1) * (other.X2 - other.X1) == (other.Y2 - other.Y1) * (other.X1 - X1) && X1.IsBetween(other.X1, other.X2) && Y1.IsBetween(other.Y1, other.Y2)) { return(true); } // check if (X2, Y2) lies on the other line if ((other.Y1 - Y2) * (other.X2 - other.X1) == (other.Y2 - other.Y1) * (other.X1 - X2) && X2.IsBetween(other.X1, other.X2) && Y2.IsBetween(other.Y1, other.Y2)) { return(true); } // check if other’s (X1, Y1) lies on this line if ((Y1 - other.Y1) * (X2 - X1) == (Y2 - Y1) * (X1 - other.X1) && other.X1.IsBetween(X1, X2) && other.Y1.IsBetween(Y1, Y2)) { return(true); } // check if other’s (other.X2, other.Y2) lies on other.line if ((Y1 - other.Y2) * (X2 - X1) == (Y2 - Y1) * (X1 - other.X2) && other.X2.IsBetween(X1, X2) && other.Y2.IsBetween(Y1, Y2)) { return(true); } return(false); }