点到线段的距离2

发布时间 2023-11-03 22:51:25作者: yanghui01

几种要考虑的情况

1) 点和线段两端重叠的情况

2) 点在线段两侧的情况

  

p在另一侧的情况以此类推

3) 点在线段中间的情况

  

 

//点到线段的距离
public static float PointToSegmentDistance2(Vector2 p, Vector2 a, Vector2 b)
{
    //点和线段端点重合
    var ap = p - a;
    if (Mathf.Approximately(ap.sqrMagnitude, 0)) //float.Epsilon
        return 0;

    var bp = p - b;
    if (Mathf.Approximately(bp.sqrMagnitude, 0))
        return 0;

    //点在线段两端
    var ab = b - a;
    if (Vector2.Dot(ap, ab) <= 0) //夹角在[90, 180]时, 距离为ap的长度
        return ap.magnitude;

    var ba = -ab;
    if (Vector2.Dot(ba, bp) <= 0) //夹角在[90, 180]时, 距离为bp的长度
        return bp.magnitude;

    //点在线段中间, 先用叉乘求出三角形面积, s*2=|ap×ab|
    float s2 = ap.x * ab.y - ap.y * ab.x;

    //再根据s*2=底*高, 求出高
    float result = s2 / ab.magnitude;
    return result;
}