Math Helper Function: findIntersection

Hey all,

I’ve been searching forums for some time now to find a function that gives me the intersection point of 2 lines. After trying out many function i finally found one that works, and thought i’d share it.

It’s a lua port of an actionscript function by Keith Hair

[code]
– calculates intersection and checks for parallel lines.
– also checks that the intersection point is actually on
– the line segment AB-EF
function findIntersection(A, B, E, F)
local ip,
a1,a2,
b1,b2,
c1,c2

a1= B.y-A.y;
b1= A.x-B.x;
c1= B.x*A.y - A.x*B.y;
a2= F.y-E.y;
b2= E.x-F.x;
c2= F.x*E.y - E.x*F.y;

– check if we are intersecting
local denom =a1*b2 - a2*b1;
if (denom == 0) then
return nil;
end

– set the intersection point
ip = {x = (b1*c2 - b2*c1)/denom, y = (a2*c1 - a1*c2)/denom}

– Double check if we are actually intersecting
if (math.pow((ip.x - B.x) + (ip.y - B.y), 2) > math.pow((A.x - B.x) + (A.y - B.y), 2)) then
return nil;
end
if (math.pow((ip.x - A.x) + (ip.y - A.y), 2) > math.pow((A.x - B.x) + (A.y - B.y), 2)) then
return nil;
end

if (math.pow((ip.x - F.x) + (ip.y - F.y), 2) > math.pow((E.x - F.x) + (E.y - F.y), 2)) then
return nil;
end
if (math.pow((ip.x - E.x) + (ip.y - E.y), 2) > math.pow((E.x - F.x) + (E.y - F.y), 2)) then
return nil;
end

return ip
end
[/code] [import]uid: 59229 topic_id: 10498 reply_id: 310498[/import]