【问题标题】:How can i find shortest point on a polygon from a point to that polygon (not it's distance )我怎样才能找到多边形上从一个点到那个多边形的最短点(不是距离)
【发布时间】:2014-07-03 11:00:04
【问题描述】:

我有一个可能在多边形内部或外部的点,我需要从该点找到多边形上最短的点。

提前感谢

【问题讨论】:

  • 到目前为止你的进展如何?请显示一些代码。
  • 您好,欢迎来到 Stack Overflow。请编辑您的帖子,以包含您迄今为止解决问题的尝试,以及您收到的结果和错误。

标签: java javascript polygon point shortest


【解决方案1】:

我不知道这是否能回答你的问题,但这是我几年前写的一段代码。
它从多边形点列表中计算点索引以及垂直线到最近边的距离。

它使用一个Vector2 结构,该结构定义了向量运算符+-*(点积)和方法GetLengthGetSquaredLength。同样的代码也应该使用Vector3 (3D) 运行。

详情请见cmets。

    // 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;
            }
        }
    }

【讨论】:

  • thanx,但我需要一个 js
  • 你没有标记它 js。它有点数学,所以将其转换为 js 应该不会很难。
猜你喜欢
  • 1970-01-01
  • 2010-10-28
  • 2021-12-06
  • 2012-06-14
  • 2020-05-10
  • 2014-07-05
  • 1970-01-01
  • 2022-08-06
  • 2021-07-20
相关资源
最近更新 更多