diff --git a/glm/gtx/closest_point.hpp b/glm/gtx/closest_point.hpp index d0f17155..eb893291 100644 --- a/glm/gtx/closest_point.hpp +++ b/glm/gtx/closest_point.hpp @@ -56,6 +56,13 @@ namespace glm detail::tvec3 const & point, detail::tvec3 const & a, detail::tvec3 const & b); + + /// 2d lines work as well + template + GLM_FUNC_DECL detail::tvec2 closestPointOnLine( + detail::tvec2 const & point, + detail::tvec2 const & a, + detail::tvec2 const & b); /// @} }// namespace glm diff --git a/glm/gtx/closest_point.inl b/glm/gtx/closest_point.inl index b13370b2..889b75b1 100644 --- a/glm/gtx/closest_point.inl +++ b/glm/gtx/closest_point.inl @@ -28,4 +28,25 @@ namespace glm if(Distance >= LineLength) return b; return a + LineDirection * Distance; } + + template + GLM_FUNC_QUALIFIER detail::tvec2 closestPointOnLine + ( + detail::tvec2 const & point, + detail::tvec2 const & a, + detail::tvec2 const & b + ) + { + T LineLength = distance(a, b); + detail::tvec2 Vector = point - a; + detail::tvec2 LineDirection = (b - a) / LineLength; + + // Project Vector to LineDirection to get the distance of point from a + T Distance = dot(Vector, LineDirection); + + if(Distance <= T(0)) return a; + if(Distance >= LineLength) return b; + return a + LineDirection * Distance; + } + }//namespace glm