Last active
November 4, 2015 11:06
-
-
Save jrialland/25e4bf6b3a88a5600b18 to your computer and use it in GitHub Desktop.
Gives the intersection point between 2 2d segments, handling all cases
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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