亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

點與線段之間的最短距離

點與線段之間的最短距離

點與線段之間的最短距離我需要一個基本的函數來找到點和線段之間的最短距離??梢噪S意用您想要的任何語言編寫解決方案;我可以將其翻譯成我正在使用的語言(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 關注
  • 1386 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號