whats new ¦  programming tips ¦  indy articles ¦  intraweb articles ¦  informations ¦  links ¦  interviews
 misc ¦  tutorials ¦  Add&Win Game

Tips (1541)

Database (90)
Files (137)
Forms (107)
Graphic (114)
IDE (21)
Indy (5)
Internet / LAN (130)
IntraWeb (0)
Math (76)
Misc (126)
Multimedia (45)
Objects/
ActiveX (51)

OpenTools API (3)
Printing (35)
Strings (83)
System (266)
VCL (242)

Top15

Tips sort by
component


Search Tip

Add new Tip

Add&Win Game

Advertising

48 Visitors Online


 
...Determine if two segments are intersecting?
Autor: Arash Partow
Homepage: http://www.partow.net
[ Print tip ]  

Tip Rating (13):  
     


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 < x4) or (x3 < LowerX) then
      
Exit;
  end
  else if 
(Upperx < x3) or (x4 < LowerX) 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 < y4) or (y3 < LowerY) then
      
Exit;
  end
  else if 
(UpperY < y3) or (y4 < LowerY) 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 < f) 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 < f) 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)) <= 0) and
  ((Orientation(x3,y3, x4,y4, x1,y1) * Orientation(x3,y3, x4,y4, x2,y2)) <= 0)
  );
*)
end;
(* End of SegmentIntersect *)


 

Rate this tip:

poor
very good


Copyright © by SwissDelphiCenter.ch
All trademarks are the sole property of their respective owners