计算点到直线的距离

直线P由点P1(x1, y1), P2(x2, y2)定义,点P3(x3, y3)是空间内一点

直线P定义为:P =  P1 + u(P2 - P1)

t是点P3到直线P的垂线

由图可知,向量P3 t与向量P1P2垂直

则 (P3-t) dot (P2-P1) = 0

因为t为P上的一点,未知参数为u

即 (P3 - (P1 + u(P2 - P1))) dot (P2-P1) = 0

可求得 u = (x3 - x1)(x2 - x1)(y3-y1)(y2-y1) / ((x2 - x1)^2 + (y2 - y1)^2)

根据u可知t的坐标,此时求点P3到点t的距离即为P3到直线P的距离

c++ 代码如下

 1 float minimum_distance(vec2 v, vec2 w, vec2 p) {
 2   // Return minimum distance between line segment vw and point p
 3   const float l2 = length_squared(v, w);  // i.e. |w-v|^2 -  avoid a sqrt
 4   if (l2 == 0.0) return distance(p, v);   // v == w case
 5   // Consider the line extending the segment, parameterized as v + t (w - v).
 6   // We find projection of point p onto the line. 
 7   // It falls where t = [(p-v) . (w-v)] / |w-v|^2
 8   const float t = dot(p - v, w - v) / l2;
 9   const vec2 projection = v + t * (w - v);  // Projection falls on the segment
10   return distance(p, projection);
11 }

 

posted @ 2019-07-06 14:26  roov  阅读(5)  评论(0编辑  收藏  举报