不同位置的点P在线段AB的投影图示如下:
代码参考如下:
static public Vector3 GetPointProjectOnSegment(Vector3 point, Vector3 pSegA, Vector3 pSegB)
{
Vector3 AB = pSegB - pSegA;
Vector3 AP = point - pSegA;
float t = Vector3.Dot(AP, AB) / Vector3.Dot(AB, AB);
Vector3 projection;
if (t < 0)
{
projection = pSegA;
}
else if (t > 1)
{
projection = pSegB;
}
else
{
projection = pSegA + t * AB;
}
return projection;
}