Last active
January 28, 2017 06:18
-
-
Save cbscribe/75654d153af12a183dfca6478f11d5fe to your computer and use it in GitHub Desktop.
find the closest point on a line to a given point
This file contains hidden or 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_closest_point(a, b, p, clamp_to_segment=True): | |
""" get closest point on line segment [ab] to point p """ | |
ab = b - a # vector from a -> b | |
ap = p - a # vector from a -> p | |
ab2 = ab.x ** 2 + ab.y ** 2 # length of ab | |
ap_dot_ab = ap.x * ab.x + ap.y * ab.y # dot product (project ap onto ab) | |
t = ap_dot_ab / ab2 | |
if clamp_to_segment: | |
if t < 0: | |
t = 0 | |
elif t > 1: | |
t = 1 | |
closest = a + ab * t | |
return closest |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment