计算线段上距离指定点最近的点

原始记录时间:2023年4月22日

计算线段上距离指定点最近的点

/// <summary>
/// 计算线段上距离指定点最近的点
/// </summary>
public static Vector3 ClosestPointOnSegment(Vector3 point, Vector3 start, Vector3 end)
{
    Vector3 direction = end - start;
    float lineLengthSquared = direction.sqrMagnitude;
    
    // 如果线段长度为0,则返回线段的起点
    if (lineLengthSquared == 0f)
        return start;
    
    float projection = Mathf.Clamp01(Vector3.Dot(point - start, direction) / lineLengthSquared);
    
    return start + direction * projection;
}

补充:通过 Mathf.Clamp01 将投影限制在 [0,1] 区间,确保最近点始终在线段上(而非延长线上)。sqrMagnitude 避免开平方运算,提升性能。