Keywords: Math, point to line, perpendicular distance

Describtion:
Known location of points `A`, `B` and `C`, calculate the shortest distance (perpendicular distance) of point `A` and line `BC`.

Source:

``````double computeDistance(vec3 A, vec3 B, vec3 C)
{
vec3 d = (C - B) / C.distance(B);
vec3 v = A - B;
double t = v.dot(d);
vec3 P = B + t * d;
return P.distance(A);
}
``````
##### Unreal Math API

`|` means dot product.

``````/**
* Returns closest point on a segment to a given point.
* The idea is to project point on line formed by segment.
* Then we see if the closest point on the line is outside of segment or inside.
*
* @param   Point           point for which we find the closest point on the segment
* @param   StartPoint      StartPoint of segment
* @param   EndPoint        EndPoint of segment
*
* @return  point on the segment defined by (StartPoint, EndPoint) that is closest to Point.
*/
FVector FMath::ClosestPointOnSegment(const FVector &Point, const FVector &StartPoint, const FVector &EndPoint)
{
const FVector Segment = EndPoint - StartPoint;
const FVector VectToPoint = Point - StartPoint;

// See if closest point is before StartPoint
const float Dot1 = VectToPoint | Segment;
if( Dot1 <= 0 )
{
return StartPoint;
}

// See if closest point is beyond EndPoint
const float Dot2 = Segment | Segment;
if( Dot2 <= Dot1 )
{
return EndPoint;
}

// Closest Point is within segment
return StartPoint + Segment * (Dot1 / Dot2);
}
``````

`He was still too young to know that the heart's memory eliminates the bad and magnifies the good, and that thanks to this artifice we manage to endure the burden of the past. ― Gabriel García Márquez, Love in the Time of Cholera`