//3d //Same math as in 2d case public static MyVector3 GetClosestPointOnLine(Edge3 e, MyVector3 p, bool withinSegment) { MyVector3 a = e.p1; MyVector3 b = e.p2; //Assume the line goes from a to b MyVector3 ab = b - a; //Vector from start of the line to the point outside of line MyVector3 ap = p - a; //The normalized "distance" from a to the closest point, so [0,1] if we are within the line segment float distance = MyVector3.Dot(ap, ab) / MyVector3.SqrMagnitude(ab); ///This point may not be on the line segment, if so return one of the end points float epsilon = MathUtility.EPSILON; if (withinSegment && distance < 0f - epsilon) { return(a); } else if (withinSegment && distance > 1f + epsilon) { return(b); } else { //This works because a_b is not normalized and distance is [0,1] if distance is within ab return(a + ab * distance); } }