从一个三维点到线段的距离如何计算?

13

我有一个三维点P和由A和B定义的线段(A是线段的起点,B是终点)。

我想计算P到线段AB之间的最短距离。

计算点到无限直线的距离很容易,因为在Wolfram Mathworld上有解决方案,我已经实现了这种方法,但我需要针对有限长度的线段进行计算。

尽管我寻找了很多方法,但我仍无法找到一个可靠的在三维中的解决方案。

我已经使用一个包含浮点数x、y和z的结构体,在C++中实现了计算点积、叉积、大小等算法。

任何一种语言的伪代码、链接或代码都可以。


softSurfer有一个很好的教程,展示了如何在2D和3D中计算点到线、射线或线段的距离 - Reed Copsey
这里有一个Mathematica的解决方案,适用于3D(或2D)https://dev59.com/fXRA5IYBdhLWcg3wuAcp#4165840 - Dr. belisarius
3个回答

13

Java函数

/**
 * Calculates the euclidean distance from a point to a line segment.
 *
 * @param v     the point
 * @param a     start of line segment
 * @param b     end of line segment 
 * @return      distance from v to line segment [a,b]
 *
 * @author      Afonso Santos
 */
 public static
 double
 distanceToSegment( final R3 v, final R3 a, final R3 b )
 {
   final R3 ab  = b.sub( a ) ;
   final R3 av  = v.sub( a ) ;

   if (av.dot(ab) <= 0.0)           // Point is lagging behind start of the segment, so perpendicular distance is not viable.
     return av.modulus( ) ;         // Use distance to start of segment instead.

   final R3 bv  = v.sub( b ) ;

   if (bv.dot(ab) >= 0.0)           // Point is advanced past the end of the segment, so perpendicular distance is not viable.
     return bv.modulus( ) ;         // Use distance to end of the segment instead.

   return (ab.cross( av )).modulus() / ab.modulus() ;       // Perpendicular distance of point to segment.
}

整个(自包含的)R3 3D代数学包的要点: https://gist.github.com/reciprocum/4e3599a9563ec83ba2a63f5a6cdd39eb

是开源库https://sourceforge.net/projects/geokarambola/的一部分。


6

这很简单。首先,将你的线段视为无限长,并找到在线上的点R,使得从R处向垂直于该线的方向延伸的射线穿过你的点P。如果R在线段AB之间,则最短距离是PR。否则,最短距离是PA和PB中较小的那个。


0

我知道这个问题有点老了,但是为了帮助其他人:

在这里,您可以找到伪代码的链接(请查看点到射线或线段的距离):

伪代码和C++实现

多种语言实现的链接(请查看贡献的实现):

C、VBA、Java和其他实现


无效的链接,代码是2D的,问题是3D的。 - oOo
这本书似乎不是免费的。 - Serge Rogatch

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接