点到线段的距离

发布时间 2023-10-18 23:41:36作者: yanghui01

情况1

情况2

情况3

情况4

 

public static float PointToLineSegmentDistance(Vector2 P, Vector2 A, Vector2 B)
{
    float a = Vector2.Distance(A, B);
    float b = Vector2.Distance(A, P);
    float c = Vector2.Distance(B, P);

    if (b <= float.MinValue || c <= float.MinValue) //与线段的开始或结束点重合
        return 0.0f;

    if (a <= float.MinValue || (c * c >= a * a + b * b))
        return b;

    if (b * b >= a * a + c * c)
        return c;

    // 海伦公式求面积
    // 返回点到线的距离(利用三角形面积公式求高)
    double p = (a + b + c) / 2.0f;
    double s = Math.Sqrt(p * (p - a) * (p - b) * (p - c));
    return (float)(2.0f * s / a);
}