点到线的距离(2D)和交点的坐标

Point to Line distance (2D) and Coordintates of intersection

本文关键字:坐标 距离 2D      更新时间:2023-10-16

所以我需要知道从一个点到一条线的距离(在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/