Intersecting Lines

Tessting a function to test whether a line intersects with a quad.

-- returns a list of points where the specified line segment intersects 
-- with the specified Quad

on mLineIntersectsQuad (me, p1, p2, aQuad)
  resultList = []
  repeat with side = 1 to 4
    -- get the line segment
    p3 = aQuad[side]
    if side < 4 then p4 = aQuad[side+1]
    else p4 =aQuad[1]
    res = me._getPointofIntersection(p1,p2,p3,p4)
    if res.ilk = #point then resultList.append( res )
  end repeat
  return resultList
end



on _getPointofIntersection (me, p1,p2,p3,p4)

  denominator = (p4.locV-p3.locV)*(p2.locH-p1.loch) - (p4.locH-p3.locH)*(p2.locV-p1.locV)
  if denominator = 0 then return 0 -- lines a parallel
  num1 = (p4.locH-p3.locH)*(p1.locV-p3.locV) - (p4.locV-p3.locV)*(p1.locH-p3.locH)
  num2 = (p2.locH-p1.locH)*(p1.locV-p3.locV) - (p2.locV-p1.locV)*(p1.locH-p3.locH)
  Ua = num1/float(denominator)
  Ub = num2/float(denominator)

  if (Ua >= 0 AND Ua < 1) AND  (Ub >= 0 AND Ub < 1) then
    x = p1.locH + ua * (p2.locH - p1.locH) 
    y = p1.locV + ua * (p2.locV - p1.locV)
    return point(x,y)

  else return 0
end

For more handy intersection functions, see "XLIB":/Codelib/xlib
First published 17/01/2006