为了账号安全,请及时绑定邮箱和手机立即绑定

点与线段之间的最短距离

点与线段之间的最短距离

点与线段之间的最短距离我需要一个基本的函数来找到点和线段之间的最短距离。可以随意用您想要的任何语言编写解决方案;我可以将其翻译成我正在使用的语言(Javascript)。编辑:我的线段由两个端点定义。所以我的线段AB是由两点定义的。A (x1,y1)和B (x2,y2)..我想找出这段线段和一个点之间的距离C (x3,y3)..我的几何技能是生疏的,所以我看到的例子是混乱的,我很抱歉承认。
查看完整描述

3 回答

?
呼啦一阵风

TA贡献1802条经验 获得超6个赞

这里有一些正确的代码,在C+中。它假定一个二维向量类。class vec2 {float x,y;},本质上是通过运算符来添加、减法、缩放等,以及一个距离和点乘积函数。x1 x2 + y1 y2).

float minimum_distance(vec2 v, vec2 w, vec2 p) {
  // Return minimum distance between line segment vw and point p
  const float l2 = length_squared(v, w);  // i.e. |w-v|^2 -  avoid a sqrt
  if (l2 == 0.0) return distance(p, v);   // v == w case
  // Consider the line extending the segment, parameterized as v + t (w - v).
  // We find projection of point p onto the line. 
  // It falls where t = [(p-v) . (w-v)] / |w-v|^2
  // We clamp t from [0,1] to handle points outside the segment vw.
  const float t = max(0, min(1, dot(p - v, w - v) / l2));
  const vec2 projection = v + t * (w - v);  // Projection falls on the segment
  return distance(p, projection);}

编辑:我需要一个Javascript实现,所以这里没有依赖项(或注释,但它是上面的一个直接端口)。点表示为xy属性。

function sqr(x) { return x * x }function dist2(v, w) { return sqr(v.x - w.x) + sqr(v.y - w.y) }function distToSegmentSquared(p, v, w) {
  var l2 = dist2(v, w);
  if (l2 == 0) return dist2(p, v);
  var t = ((p.x - v.x) * (w.x - v.x) + (p.y - v.y) * (w.y - v.y)) / l2;
  t = Math.max(0, Math.min(1, t));
  return dist2(p, { x: v.x + t * (w.x - v.x),
                    y: v.y + t * (w.y - v.y) });}function distToSegment(p, v, w) { return Math.sqrt(distToSegmentSquared(p, v, w))
                    ; }

编辑2:我需要一个Java版本,但更重要的是,我需要3D版本而不是2d版本。

float dist_to_segment_squared(float px, float py, float pz, float lx1, float ly1, float lz1, float lx2, float ly2, float lz2) {
  float line_dist = dist_sq(lx1, ly1, lz1, lx2, ly2, lz2);
  if (line_dist == 0) return dist_sq(px, py, pz, lx1, ly1, lz1);
  float t = ((px - lx1) * (lx2 - lx1) + (py - ly1) * (ly2 - ly1) + (pz - lz1) * (lz2 - lz1)) / line_dist;
  t = constrain(t, 0, 1);
  return dist_sq(px, py, pz, lx1 + t * (lx2 - lx1), ly1 + t * (ly2 - ly1), lz1 + t * (lz2 - lz1));}


查看完整回答
反对 回复 2019-06-06
  • 3 回答
  • 0 关注
  • 1271 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信