I'm using the line intersection code here: https://love2d.org/wiki/Additional_math, and am having trouble with it when line segments are horizontal or vertical.
In the part where it checks the segments, the checks sometimes return false when the three values are identical. I have no idea why. I ended up adding a tolerance value of 0.1, which did the trick but should be unnecessary. Any idea why this would be happening?
Attached is a love file that turns on and off the tolerance with the space button. WASD or arrows move the rectangle. When the tolerance is off, the collision is missed at random-seeming times.
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, tol)
-- added tolerance
local tolerance = tol and 0.1 or 0
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 = a1*b2 - a2*b1
if det==0 then return false, "The lines are parallel." end
local 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 + tolerance and x <= max(l1p1x,l1p2x) + tolerance and min(l1p1y,l1p2y) <= y + tolerance
and y <= (max(l1p1y,l1p2y)) + tolerance) or
seg2 and not (min(l2p1x,l2p2x) <= x + tolerance and x <= max(l2p1x,l2p2x) + tolerance and min(l2p1y,l2p2y) <= y + tolerance
and y <= (max(l2p1y,l2p2y)) + tolerance) then
return false, "The lines don't intersect."
end
end
return x,y
end