计算点到直线的距离

2D 中 (C)
参考:https://www.cnblogs.com/yushuo/p/9304218.html

//点PCx,PCy到线段PAx,PAy,PBx,PBy的距离
double GetNearestDistance(double PAx, double PAy,double PBx, double PBy,double PCx, double PCy)
{     
    double a,b,c;  
    a=getDistanceBtwP(PAy,PAx,PBy,PBx);//经纬坐标系中求两点的距离公式
    b=getDistanceBtwP(PBy,PBx,PCy,PCx);//经纬坐标系中求两点的距离公式
    c=getDistanceBtwP(PAy,PAx,PCy,PCx);//经纬坐标系中求两点的距离公式
    if(b*b>=c*c+a*a)return c;   
    if(c*c>=b*b+a*a)return b;  
    double l=(a+b+c)/2;     //周长的一半   
    double s=sqrt(l*(l-a)*(l-b)*(l-c));  //海伦公式求面积 
    return 2*s/a;   
}

3D 中(C#)
参考:https://www.jianshu.com/p/8ba826e6208a

public static float distancePoint2Line(Vector3 point, Vector3 linePoint1, Vector3 linePoint2)
{
    float fProj = Vector3.Dot(point - linePoint1, (linePoint1 - linePoint2).normalized);
    return Mathf.Sqrt((point - linePoint1).sqrMagnitude - fProj * fProj);
}

标签: none

添加新评论