Finding the intersecting point of two lines

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
User avatar
Pordrack
Prole
Posts: 13
Joined: Tue Sep 04, 2018 5:23 pm

Finding the intersecting point of two lines

Post by Pordrack »

Hello ! Do you know if there's a way to find the intersecting point of two lines, using the x and y of the start and end point of each line ? Like a function, or a library for lua. I searched for mathematic solutions, but the one I found require the line's equations, which I don't have and don't really know how to get. The lines I use have a fixed length but a "dynamic" angle which I know.
MrFariator
Party member
Posts: 512
Joined: Wed Oct 05, 2016 11:53 am

Re: Finding the intersecting point of two lines

Post by MrFariator »

On the love2d wiki there is a general math page, and it contains the following function:

Code: Select all

-- Checks if two lines intersect (or line segments if seg is true)
-- Lines are given as four numbers (two coordinates)
function math.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
So if you want to know if the lines intersect between their start and end points (presented in two sets of x and y values of each point), just pass "true" to the seg1 and seg2 parameters; otherwise the function will figure out the point at which the lines will intersect (as though they go on forever). Or you can just remove the if-then statement from the function to simplify its use.
User avatar
Pordrack
Prole
Posts: 13
Joined: Tue Sep 04, 2018 5:23 pm

Re: Finding the intersecting point of two lines

Post by Pordrack »

Thanks a lot
Post Reply

Who is online

Users browsing this forum: No registered users and 216 guests