Unity点到线段的最短距离

抄的Unity的源码

HandleUtility.DistancePointLine 是UnityEditor代码,源码如下,这样就可以在Runtime中运行

注意性能开销!

 

    /// <summary>
    /// 计算点到线段的最短距离
    /// </summary>
    /// <param name="point"></param>
    /// <param name="lineStart"></param>
    /// <param name="lineEnd"></param>
    /// <returns></returns>
    public static float DistancePointLine(Vector3 point, Vector3 lineStart, Vector3 lineEnd)
    {
        Vector3 rhs = point - lineStart;
        Vector3 vector3 = lineEnd - lineStart;
        float magnitude = vector3.magnitude;
        Vector3 lhs = vector3;
        if ((double) magnitude > 9.99999997475243E-07)
            lhs /= magnitude;
        float num = Mathf.Clamp(Vector3.Dot(lhs, rhs), 0.0f, magnitude);
        Vector3 v3 = lineStart + lhs * num;
        return Vector3.Magnitude (v3 - point);
    }

 

 

向量计算法:

AB为向量,求C到AB的距离,计算向量AC在向量AB上投影得到AD,可计算DC的长度

性能没问题

    float GetPointToLineDistance(Vector3 point, Vector3 start, Vector3 end) {
        Vector3 sp = point - start;
        Vector3 se = end - start;
        Vector3 project = Vector3.Project (sp, se);
        Vector3 line = sp - project;
        return line.magnitude;
    }

 俯视角二维

    private float GetPointToPlaneDistance(Vector3 point, Vector3 start, Vector3 end) {
        point = new Vector3 (point.x, 0, point.z);
        start = new Vector3 (start.x, 0, start.z);
        end = new Vector3 (end.x, 0, end.z);
        
        Vector3 sp = point - start;
        Vector3 se = end - start;
        Vector3 project = Vector3.Project (sp, se);
        Vector3 line = sp - project;
        return line.magnitude;
    }

 

 

胶囊体计算法:

上面的方法计算量较大,这种是实际项目中用的一种

 

posted @ 2021-06-04 17:00  三页菌  阅读(798)  评论(0编辑  收藏  举报