Detect 2D line intersections by IanM23rd Sep 2003 14:35
|
---|
Summary Want to find out if your lines cross each other? Where they do or will cross? If they overlap? Then go no further :) Description There are 3 functions included here Code ` This code was downloaded from The Game Creators ` It is reproduced here with full permission ` http://www.thegamecreators.com type Intersection_t Intersect as integer X as float Y as float Parallel as integer Colinear as integer Overlap as integer endtype global Intersection as Intersection_t function FastLineIntersection(Ax as float, Ay as float, Bx as float, By as float, _ Cx as float, Cy as float, Dx as float, Dy as float) local r as float local s as float local d as float local n as float n = ((Ay - Cy) * (Dx - Cx)) - ((Ax - Cx) * (Dy - Cy)) d = ((Bx - Ax) * (Dy - Cy)) - ((By - Ay) * (Dx - Cx)) if d = 0 then exitfunction 0 r = n / d s = ( ((Ay-Cy)*(Bx-Ax))-((Ax-Cx)*(By-Ay)) ) / d if r <= 0 then exitfunction 0 if r >= 1 then exitfunction 0 if s <= 0 then exitfunction 0 if s >= 1 then exitfunction 0 endfunction 1 function LineIntersection( Ax as float, Ay as float, Bx as float, By as float, Cx as float, Cy as float, Dx as float, Dy as float) local r as float local s as float local d as float local n as float n = ((Ay - Cy) * (Dx - Cx)) - ((Ax - Cx) * (Dy - Cy)) d = ((Bx - Ax) * (Dy - Cy)) - ((By - Ay) * (Dx - Cx)) if d = 0 if n = 0 if Ay = By if (Ax-Cx)*(Bx-Cx) < 0 or (Ax-Dx)*(Bx-Dx) < 0 then exitfunction 1 else if (Ay-Cy)*(By-Cy) < 0 or (Ay-Dy)*(By-Dy) < 0 then exitfunction 1 endif endif exitfunction 0 endif r = n / d s = ( ((Ay-Cy)*(Bx-Ax))-((Ax-Cx)*(By-Ay)) ) / d if r <= 0 then exitfunction 0 if r >= 1 then exitfunction 0 if s <= 0 then exitfunction 0 if s >= 1 then exitfunction 0 endfunction 1 function FullLineIntersection(Ax as float, Ay as float, Bx as float, By as float, _ Cx as float, Cy as float, Dx as float, Dy as float) local r as float local s as float local d as float local n as float Intersection.Intersect = 0 n = ((Ay-Cy)*(Dx-Cx))-((Ax-Cx)*(Dy-Cy)) d = ((Bx-Ax)*(Dy-Cy))-((By-Ay)*(Dx-Cx)) if d = 0 Intersection.X = 0.0 Intersection.Y = 0.0 Intersection.Parallel = 1 if n = 0 Intersection.Colinear = 1 Intersection.Overlap = 0 if Ay = By if (Ax-Cx)*(Bx-Cx) < 0 or (Ax-Dx)*(Bx-Dx) < 0 then Intersection.Overlap=1 else if (Ay-Cy)*(By-Cy) < 0 or (Ay-Dy)*(By-Dy) < 0 then Intersection.Overlap=1 endif else Intersection.Colinear = 0 Intersection.Overlap = 0 endif else r = n / d s = ( ((Ay-Cy)*(Bx-Ax))-((Ax-Cx)*(By-Ay)) ) / d if r > 0 then if r < 1 if s > 0 then if s < 1 Intersection.Intersect = 1 endif endif Intersection.X = Ax + (r * (Bx - Ax) ) Intersection.Y = Ay + (r * (By - Ay) ) Intersection.Parallel = 0 Intersection.Colinear = 0 Intersection.Overlap = 0 endif endfunction Intersection.Intersect |