Code: Select all
-- Checks if two lines intersect (or line segments if seg is true)
-- Lines are given as four numbers (two coordinates)
function findIntersect(l1p1x,l1p1y, l1p2x,l1p2y, l2p1x,l2p1y, l2p2x,l2p2y, seg1, seg2)
local a1,b1,a2,b2 = l1p2y-l1p1y, l1p1x-l1p2x, l2p2y-l2p1y, l2p1x-l2p2x
local c1,c2 = a1*l1p1x+b1*l1p1y, a2*l2p1x+b2*l2p1y
local det,x,y = a1*b2 - a2*b1
if det==0 then return false, "The lines are parallel." end
x,y = (b2*c1-b1*c2)/det, (a1*c2-a2*c1)/det
if seg1 or seg2 then
local min,max = math.min, math.max
if seg1 and not (min(l1p1x,l1p2x) <= x and x <= max(l1p1x,l1p2x) and min(l1p1y,l1p2y) <= y and y <= max(l1p1y,l1p2y)) or
seg2 and not (min(l2p1x,l2p2x) <= x and x <= max(l2p1x,l2p2x) and min(l2p1y,l2p2y) <= y and y <= max(l2p1y,l2p2y)) then
return false, "The lines don't intersect."
end
end
return x,y
end
Trying to debug the thing, I'm printing out the coordinates of lines i'm testing with. Take this case where I'm calling the function with:
Code: Select all
l1p1x = 255.9
l1p1y = 600
l1p2x = 105.9
l1p2y = 0
l2p1x = 267.8
l2p1y = 400
l2p2x = 100
l2p2y = 400
seg1 = true
seg2 = true
Does anyone have a clue into what's happening? Is the algorithm somehow expecting points or lines in some certain direction/order perhaps?