Skip to content

Instantly share code, notes, and snippets.

@you-ssk
Last active August 29, 2015 14:28
Show Gist options
  • Save you-ssk/fcc43fba48d68de40622 to your computer and use it in GitHub Desktop.
Save you-ssk/fcc43fba48d68de40622 to your computer and use it in GitHub Desktop.
require 'matrix'
def line_intersection line1, line2
l1 = line1.map{|v|v.map(&:to_f)}
l2 = line2.map{|v|v.map(&:to_f)}
a = l1[1]-l1[0]
b = l2[1]-l2[0]
ab = l1[0]-l2[0]
cab = a.cross(b)
nA = b.cross(ab).dot(cab)
nB = a.cross(ab).dot(cab)
d = a.cross(b).dot(cab)
nAd = nA/d
nBd = nB/d
return nil if !(0..1).include?(nAd) || !(0..1).include?(nBd)
a0 = l1[0]+a*nAd
b0 = l2[0]+b*nBd
if (a0-b0).magnitude < 0.001
return a0
else
nil
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment