Point of intersection between 2 lines

From Director Online Wiki
Jump to: navigation, search

function to determine the intersect point between 2 lines.

-- p1, p2 -- start and endpoint of first line
-- p3, p4 -- start and endpoint of second line
on PointofIntersection p1,p2,p3,p4
  denominator = (p4[2]-p3[2])*(p2[1]-p1[1]) - (p4[1]-p3[1])*(p2[2]-p1[2])
  if denominator = 0 then return 0 
  num1 = (p4[1]-p3[1])*(p1[2]-p3[2]) - (p4[2]-p3[2])*(p1[1]-p3[1])
  num2 = (p2[1]-p1[1])*(p1[2]-p3[2]) - (p2[2]-p1[2])*(p1[1]-p3[1])
  Ua = num1/float(denominator)
  Ub = num2/float(denominator)
  if (Ua >= 0 AND Ua < 1) AND  (Ub >= 0 AND Ub < 1) then
    x = p1[1] + ua * (p2[1] - p1[1]) 
    y = p1[2] + ua * (p2[2] - p1[2])
    return point(x,y)
  else return -1
end