Skip to content

Instantly share code, notes, and snippets.

@ostr00000
Created January 24, 2022 14:26
Show Gist options
  • Save ostr00000/3a8fcf66fdf31a3790a40fe1aa377e5a to your computer and use it in GitHub Desktop.
Save ostr00000/3a8fcf66fdf31a3790a40fe1aa377e5a to your computer and use it in GitHub Desktop.
2D version for finding the shortest distance between a point and line segments. Based on https://stackoverflow.com/a/51240898 and http://www.fundza.com/vectors/point2line/index.html.
import math
def dot(v, w):
x, y = v
X, Y = w
return x * X + y * Y
def length(v):
x, y = v
return math.sqrt(x * x + y * y)
def vector(b, e):
x, y = b
X, Y = e
return X - x, Y - y
def unit(v):
x, y = v
mag = length(v)
return x / mag, y / mag
def distance(p0, p1):
return length(vector(p0, p1))
def scale(v, sc):
x, y = v
return x * sc, y * sc
def add(v, w):
x, y = v
X, Y = w
return x + X, y + Y
def pnt2line(pnt, start, end):
line_vec = vector(start, end)
pnt_vec = vector(start, pnt)
line_len = length(line_vec)
line_unit_vec = unit(line_vec)
pnt_vec_scaled = scale(pnt_vec, 1.0 / line_len)
t = dot(line_unit_vec, pnt_vec_scaled)
if t < 0.0:
t = 0.0
elif t > 1.0:
t = 1.0
nearest = scale(line_vec, t)
dist = distance(nearest, pnt_vec)
nearest = add(nearest, start)
return dist, nearest
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment