点到线的距离(2D)和交点的坐标
Point to Line distance (2D) and Coordintates of intersection
所以我需要知道从一个点到一条线的距离(在2D空间中),给定线的两个坐标(AB)。
以下是我目前所拥有的:
public double pointToLineDistance(Point A, Point B, Point P)
{
double normalLength = Math.sqrt((B.x - A.x) * (B.x - A.x) + (B.y - A.y) * (B.y - A.y));
return Math.abs((P.x - A.x) * (B.y - A.y) - (P.y - A.y) * (B.x - A.x)) / normalLength;
}
但我也需要得到垂直线与AB线相交的点的坐标(如果它在这个线段之外也可以)。
有什么想法吗?
观察AB可以表示为
ab = A + (B - A) * s
因此,AB的方向是B - A
,或(B.x - A.x, B.y - A.y)
。方向为(A.y - B.y, B.x - A.x)
的线将是垂直的。(我们只是交换x和y,并否定其中一个。)
我们特别想要一条垂直于AB并穿过p的线,所以我们做
perp = P + (A.y - B.y, B.x - A.x) * t;
perp = (P.x + A.y - B.y, P.y + B.x - A.x) * t;
现在只要找到这条垂线和AB之间的交点。你有两个方程(对于交点的x和y分量)和两个未知数(s和t)。一旦你找到了s和t,就把它们代入其中一条线的方程中,得到交点。
以下是一些工作代码:
static Vect2 getIntersection(Vect2 A, Vect2 B, Vect2 P) {
Vect2 abDir = B.minus(A);
Vect2 perpDir = new Vect2(-abDir.y, abDir.x);
Vect2 apDir = P.minus(A);
double s = (perpDir.y * apDir.x - perpDir.x * apDir.y)
/ (abDir.x * perpDir.y - abDir.y * perpDir.x);
return A.plus(abDir.scale(s));
}
class Vect2 {
final double x, y;
Vect2(double x, double y) {
this.x = x;
this.y = y;
}
Vect2 scale(double k) {
return new Vect2(x * k, y * k);
}
Vect2 plus(Vect2 that) {
return new Vect2(x + that.x, y + that.y);
}
Vect2 minus(Vect2 that) {
return this.plus(that.scale(-1));
}
}
这个想法是构造一个穿过点A和B的线的方程。当你构造了这个方程时,你就构造了一个穿过p并垂直于AB的线的方程式。垂直线的方程式的系数很容易从AB线的方程式中导出。一旦你有了两个方程,求解它们就会得到交点的坐标。
这是家庭作业吗?
这会有所帮助http://paulbourke.net/geometry/pointline/
相关文章:
- QGraphicsPolygonItem在拖动时未更新QPolygonF坐标
- 如何修复此错误:未定义对"距离(浮点数,浮点数,浮点数,浮点数,浮点数)"的引用
- 在C++中使用GDAL可以将图像的像素坐标转换为lat,long吗
- UE4-如何在给定4个屏幕坐标的情况下缩放纹理或材质
- 用C++程序计算圆锥体的体积、球体的体积、八边形的面积和两点之间的距离
- 计算所有对之间的曼哈顿距离
- 如何使用发送数据包所花费的时间计算两个节点之间的距离?
- 使用C++中的链表对与原点的距离、x 和 y 坐标进行排序
- c++ 从大型数组中读取 3D 坐标并计算它们之间的距离
- 获取具有X,Y和距离的OPENCV中的3D坐标
- 找到使用球形坐标表达的线段之间的距离
- 如何按距点的距离(x1,y1)升序对一组坐标进行排序
- 在8个谜题|C++中寻找曼哈顿距离的目标坐标
- 坐标最小距离 C++
- 游戏 - 计算两个坐标之间的距离
- 点到线的距离(2D)和交点的坐标
- 求(x,y)坐标之间的最大距离
- 查找地球坐标(经纬度),距离(米)和方位(角)
- 我们如何同时使用汉明距离和坐标之间的距离来匹配特征
- 用X-Y坐标表示的点之间的最短路径距离