Skip to content

Instantly share code, notes, and snippets.

@jrialland
Last active November 4, 2015 11:06
Show Gist options
  • Save jrialland/25e4bf6b3a88a5600b18 to your computer and use it in GitHub Desktop.
Save jrialland/25e4bf6b3a88a5600b18 to your computer and use it in GitHub Desktop.
Gives the intersection point between 2 2d segments, handling all cases
def get_intersection(line1, line2):
xdiff = (line1[0][0] - line1[1][0], line2[0][0] - line2[1][0])
ydiff = (line1[0][1] - line1[1][1], line2[0][1] - line2[1][1]) #Typo was here
def det(a, b):
return a[0] * b[1] - a[1] * b[0]
div = det(xdiff, ydiff)
if div == 0:
return None
d = (det(*line1), det(*line2))
p = det(d, xdiff) / div, det(d, ydiff) / div
def onsegment(seg, p):
x1,x2=min(seg[0][0], seg[1][0]), max(seg[0][0], seg[1][0])
y1,y2=min(seg[0][1], seg[1][1]), max(seg[0][1], seg[1][1])
return x1<=p[0]<=x2 and y1<=p[1]<=y2
if onsegment(line1, p) and onsegment(line2, p):
return p
return None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment