Skip to content

Instantly share code, notes, and snippets.

@audionerd
Last active August 29, 2015 14:03
Show Gist options
  • Save audionerd/4fa499b3970e8a9bed59 to your computer and use it in GitHub Desktop.
Save audionerd/4fa499b3970e8a9bed59 to your computer and use it in GitHub Desktop.
Line Segment Intersection
# via http://stackoverflow.com/questions/563198/how-do-you-detect-where-two-line-segments-intersect
# http://mathworld.wolfram.com/Line-LineIntersection.html
getLineIntersection = (x1, y1, x2, y2, x3, y3, x4, y4) ->
s1_x = x2 - x1
s1_y = y2 - y1
s2_x = x4 - x3
s2_y = y4 - y3
s = (-s1_y * (x1 - x3) + s1_x * (y1 - y3)) / (-s2_x * s1_y + s1_x * s2_y)
t = (s2_x * (y1 - y3) - s2_y * (x1 - x3)) / (-s2_x * s1_y + s1_x * s2_y)
if (s >= 0 && s <= 1 && t >= 0 && t <= 1)
intX = x1 + (t * s1_x)
intY = y1 + (t * s1_y)
[intX, intY]
else
null
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment