簡體   English   中英

我如何在多邊形上找到從點到該多邊形的最短點(不是距離)

[英]How can i find shortest point on a polygon from a point to that polygon (not it's distance )

我有一個可能在多邊形內部或外部的點,我需要從該點中找到多邊形上的最短點。

預先感謝

我不知道這是否能回答您的問題,但這是幾年前我寫的一段代碼。
它從多邊形點列表以及垂直於最近邊緣的距離中計算出點索引。

它使用Vector2結構,該結構定義矢量運算符+-* (點積)以及方法GetLengthGetSquaredLength 相同的代碼也應與Vector3 (3D)一起運行。

請查看評論以獲取詳細信息。

    // Polygon points
    List<Vector2> p;

    /// <summary> Calculates the perpendicular vector from nearest point on polygon to given point. If no points available minIndex is -1. </summary>
    public void GetPolygonDist(Vector2 point, out Vector2 minDist, out int minIndex) {
        if (p.Count == 0) { minDist = Vector2.Null(); minIndex = -1; return; }
        Vector2 dist;
        minDist = point - p[0];
        minIndex = 0;
        for (int i = 0; i < p.Count - 1; i++) {
            Vector2 l = p[i + 1] - p[i];                                        // Edge
            if (l.GetLength() < 1e-9) continue;                                 // Ignore edge of length almost zero
            Vector2 d = point - p[i];                                           // Polygon point to point
            Vector2 b = (l * d) / (l * l) * l;                                  // Projection to edge
            double f = Math.Sign(b * l) * (b.GetLength() / l.GetLength());      // Where on the edge is the perpendicular?
            if (f < 0.0) dist = point - p[i];                                   // Point before the edge
            else if (f > 1.0) dist = point - p[i + 1];                          // Point after the edge
            else dist = d - b;                                                  // Perpendicular
            if (dist.GetSquaredLength() < minDist.GetSquaredLength()) {
                minDist = dist;
                minIndex = i;
            }
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM