Skip to content

Misnomer closestPointOnLineSegment #37

@1j01

Description

@1j01

export closestPointOnLineSegment = (point, a, b)->
# https://stackoverflow.com/a/3122532/2624876
a_to_p = {x: point.x - a.x, y: point.y - a.y}
a_to_b = {x: b.x - a.x, y: b.y - a.y}
atb2 = a_to_b.x**2 + a_to_b.y**2
atp_dot_atb = a_to_p.x*a_to_b.x + a_to_p.y*a_to_b.y
t = atp_dot_atb / atb2
return {x: a.x + a_to_b.x*t, y: a.y + a_to_b.y*t}

This function is missing clamping of t to 0-1, thus making it project onto an infinite line, not find the closest point on a line segment.

To be fair, the StackOverflow answer is misleading, it does not answer the asked question.

Anyways, I should fix closestPointOnLineSegment and expose closestPointOnInfiniteLine with the old behavior.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions