Skip to content

Instantly share code, notes, and snippets.

@cocomoff
Created December 11, 2019 09:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cocomoff/0b36353165a517168707f13eaf78fe09 to your computer and use it in GitHub Desktop.
Save cocomoff/0b36353165a517168707f13eaf78fe09 to your computer and use it in GitHub Desktop.
segments and intersect
def line_segment_intersection(p1, p2, p3, p4):
d = (p2[0] - p1[0]) * (p4[1] - p3[1]) - (p2[1] - p1[1]) * (p4[0] - p3[0])
if d == 0.0:
return None
intersect = [0.0, 0.0]
u = ((p3[0] - p1[0]) * (p4[1] - p3[1]) - (p3[1] - p1[1]) * (p4[0] - p3[0])) / d
v = ((p3[0] - p1[0]) * (p2[1] - p1[1]) - (p3[1] - p1[1]) * (p2[0] - p1[0])) / d
if u < 0.0 or u > 1.0 or v < 0.0 or v > 1.0:
return None
px = p1[0] + u * (p2[0] - p1[0])
py = p1[1] + u * (p2[1] - p1[1])
if px == p1[0] and py == p1[1] or \
px == p2[0] and py == p2[1] or \
px == p3[0] and py == p3[1] or \
px == p4[0] and py == p4[1]:
return None
return (px, py)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment