diff --git a/Source/Engine/Core/Math/CollisionsHelper.cpp b/Source/Engine/Core/Math/CollisionsHelper.cpp index 48e7472d1..3200d8962 100644 --- a/Source/Engine/Core/Math/CollisionsHelper.cpp +++ b/Source/Engine/Core/Math/CollisionsHelper.cpp @@ -41,6 +41,28 @@ void CollisionsHelper::ClosestPointPointLine(const Vector2& point, const Vector2 } } +Vector3 CollisionsHelper::ClosestPointPointLine(const Vector3& point, const Vector3& p0, const Vector3& p1) +{ + const Vector3 p = point - p0; + Vector3 n = p1 - p0; + const float length = n.Length(); + if (length < 1e-10) + { + return p0; + } + n /= length; + const float dot = Vector3::Dot(n, p); + if (dot <= 0.0) + { + return p0; + } + else if (dot >= length) + { + return p1; + } + return p0 + n * dot; +} + void CollisionsHelper::ClosestPointPointTriangle(const Vector3& point, const Vector3& vertex1, const Vector3& vertex2, const Vector3& vertex3, Vector3& result) { // Source: Real-Time Collision Detection by Christer Ericson diff --git a/Source/Engine/Core/Math/CollisionsHelper.h b/Source/Engine/Core/Math/CollisionsHelper.h index 33631a682..ee8ea2828 100644 --- a/Source/Engine/Core/Math/CollisionsHelper.h +++ b/Source/Engine/Core/Math/CollisionsHelper.h @@ -72,6 +72,15 @@ public: /// When the method completes, contains the closest point between the two objects. static void ClosestPointPointLine(const Vector2& point, const Vector2& p0, const Vector2& p1, Vector2& result); + /// + /// Determines the closest point between a point and a line. + /// + /// The point to test. + /// The line first point. + /// The line second point. + /// When the method completes, contains the closest point between the two objects. + static Vector3 ClosestPointPointLine(const Vector3& point, const Vector3& p0, const Vector3& p1); + /// /// Determines the closest point between a point and a triangle. ///