Mega Code Archive

 
Categories / Delphi / Algorithm Math
 

How to Determine if two segments are intersecting

Title: How to Determine if two segments are intersecting function Intersect(const x1, y1, x2, y2, x3, y3, x4, y4: Double): Boolean; var UpperX: Double; UpperY: Double; LowerX: Double; LowerY: Double; Ax: Double; Bx: Double; Cx: Double; Ay: Double; By: Double; Cy: Double; D: Double; F: Double; E: Double; begin Result := False; Ax := x2 - x1; Bx := x3 - x4; if Ax 0.0 then begin LowerX := x2; UpperX := x1; end else begin UpperX := x2; LowerX := x1; end; if Bx 0.0 then begin if (UpperX ) or (x3 ) then Exit; end else if (Upperx ) or (x4 ) then Exit; Ay := y2 - y1; By := y3 - y4; if Ay 0.0 then begin LowerY := y2; UpperY := y1; end else begin UpperY := y2; LowerY := y1; end; if By 0.0 then begin if (UpperY ) or (y3 ) then Exit; end else if (UpperY ) or (y4 ) then Exit; Cx := x1 - x3; Cy := y1 - y3; d := (By * Cx) - (Bx * Cy); f := (Ay * Bx) - (Ax * By); if f 0.0 then begin if (d 0.0) or (d f) then Exit; end else if (d 0.0) or (d ) then Exit; e := (Ax * Cy) - (Ay * Cx); if f 0.0 then begin if (e 0.0) or (e f) then Exit; end else if (e 0.0) or (e ) then Exit; Result := True; (* Simple method, yet not so accurate for certain situations and a little more inefficient (roughly 19.5%). Result := ( ((Orientation(x1,y1, x2,y2, x3,y3) * Orientation(x1,y1, x2,y2, x4,y4)) ((Orientation(x3,y3, x4,y4, x1,y1) * Orientation(x3,y3, x4,y4, x2,y2)) ); *) end; (* End of SegmentIntersect *)