Code: Select all
function intersect(x1, y1, x2, y2, x3, y3, x4, y4)
local x21, x43 = x2 - x1, x4 - x3
local y21, y43 = y2 - y1, y4 - y3
local d = x21 * y43 - y21 * x43
if d == 0 then return false end
local xy34 = x3 * y4 - y3 * x4
local xy12 = x1 * y2 - y1 * x2
local a = xy34 * x21 - xy12 * x43
local b = xy34 * y21 - xy12 * y43
return a / d, b / d
end
I added the last line to calculate the 'point of intersection' in addition to the intersection times:
Code: Select all
function intersect(x1, y1, x2, y2, x3, y3, x4, y4)
local dx1, dy1 = x2 - x1, y2 - y1
local dx2, dy2 = x4 - x3, y4 - y3
local dx3, dy3 = x1 - x3, y1 - y3
local d = dx1*dy2 - dy1*dx2
if d == 0 then
return -- collinear
end
local t1 = (dx2*dy3 - dy2*dx3)/d
local t2 = (dx1*dy3 - dy1*dx3)/d
return x1 + t1*dx1, y1 + t1*dy1, t1, t2
end
Code: Select all
function intersectSegment(x1, y1, x2, y2, x3, y3, x4, y4)
local dx1, dy1 = x2 - x1, y2 - y1
local dx2, dy2 = x4 - x3, y4 - y3
local dx3, dy3 = x1 - x3, y1 - y3
local d = dx1*dy2 - dy1*dx2
if d == 0 then
return -- collinear
end
local t1 = (dx2*dy3 - dy2*dx3)/d
if (t1 < 0) or (t1 > 1) then
return -- non-intersecting segment
end
local t2 = (dx1*dy3 - dy1*dx3)/d
if (t2 < 0) or (t2 > 1) then
return -- non-intersecting segment
end
return x1 + t1*dx1, y1 + t1*dy1, t1, t2
end