找到从3d点到线段的距离

ogg*_*ter 10 math 3d vector

我有一个3d点P和一个由A和B定义的线段(A是线段的起点,B是结束点).

我想计算P和AB线之间的最短距离.

计算点到无限线的距离很容易,因为它们是Wolfram Mathworld的解决方案,我已经实现了这个,但我需要为有限长度的线做这个.

经过大量的考察,我还没有在3d中找到一个可靠的解决方案.

我已经实现了算法来计算C++中的点积,交叉积,大小等,其结构包含浮点数x,y和z.

几乎所有语言中的伪代码,链接或代码都很棒.

Afo*_*tos 7

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.
}
Run Code Online (Sandbox Code Playgroud)

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

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


Tho*_*eod 5

这是相当直接的.首先,将您的线段视为无限,并找到R上线的垂直光线穿过您的点P的线上的点R.如果R在线上的A和B之间,那么最短的距离是公关.否则,最短距离是PA和PB的出租人.