找到与方向无关的两个向量的交点

find intersection point of two vectors independent from direction

我有两个向量,我想知道这些向量将在何处相交,与方向或长度无关。所以可以说我会在任一方向绘制一条无限线,我想知道这两条线将在何处相交并获得坐标。请参阅下图进行说明:

所以我想知道粉红色 X 的坐标。但我只能找到计算两条线的交点的公式,我没有 :( 所以我正在寻找一些帮助关于如何正确处理这个问题。

我已经计算出蓝线的归一化方向:像这样:

PVector norm12 = new PVector(-dir12.y, dir12.x);
PVector norm23 = new PVector(dir23.y, -dir23.x);

关于我为什么要这样做的一些背景信息: 我试图找到由 3 个点创建的圆的中心点。

所有这些都是二维的

如果需要额外信息,我很乐意提供。

如果你有一条由点 P 和归一化方向 R 定义的无限线和第二条由点 Q 定义的无限线和一个方向S,则无尽直线X的交点为:

alpha ... angle between Q-P and R
beta  ... angle between R and S

gamma  =  180° - alpha - beta

h  =  | Q - P | * sin(alpha)
u  =  h / sin(beta)

t  = | Q - P | * sin(gamma) / sin(beta)

t  =  dot(Q-P, (S.y, -S.x)) / dot(R, (S.y, -S.x))  =  determinant(mat2(Q-P, S)) / determinant(mat2(R, S))
u  =  dot(Q-P, (R.y, -R.x)) / dot(R, (S.y, -S.x))  =  determinant(mat2(Q-P, R)) / determinant(mat2(R, S))

X  =  P + R * t  =  Q + S * u

这个可以用PVector来计算,如下:

// Intersect 2 endless lines
// line 1: "P" is on endless line, the direction is "dir1" ("R")
// line 2: "Q" is on endless line, the direction is "dir2" ("S")
PVector Intersect( PVector P, PVector dir1, PVector Q, PVector dir2) {

    PVector R = dir1.copy();
    PVector S = dir2.copy();
    R.normalize();
    S.normalize();

    PVector QP  = PVector.sub(Q, P);
    PVector SNV = new PVector(S.y, -S.x);

    float t  =  QP.dot(SNV) / R.dot(SNV); 

    PVector X = PVector.add(P, PVector.mult(R, t));
    return X;
}

看例子:

void setup() {
    size(500,500);
}

void draw() {

    background(0, 0, 0);

    stroke(255);
    fill(255, 0, 0);

    PVector l1p1 = new PVector(250, 150);
    PVector l1p2 = new PVector(300, 300);
    PVector l2p1 = new PVector(200, 180);
    PVector l2p2 = new PVector(300, 220);
    PVector l3p1 = new PVector(200, 300);
    PVector l3p2 = new PVector(250, 280);

    line(l1p1.x, l1p1.y, l1p2.x, l1p2.y);
    line(l2p1.x, l2p1.y, l2p2.x, l2p2.y);
    line(l3p1.x, l3p1.y, l3p2.x, l3p2.y);

    PVector dir1 = PVector.sub(l1p2, l1p1);
    PVector dir2 = PVector.sub(l2p2, l2p1);
    PVector dir3 = PVector.sub(l3p2, l3p1);

    PVector x1 = Intersect(l1p1, dir1, l2p1, dir2);
    circle(x1.x, x1.y, 10);
    PVector x2 = Intersect(l1p1, dir1, l3p1, dir3);
    circle(x2.x, x2.y, 10);
    PVector x3 = Intersect(l2p1, dir2, l3p1, dir3);
    circle(x3.x, x3.y, 10);
}

注意,如果直线平行,则返回点(PVector 对象)的标量是无穷大。这可以通过Float.isInfinite来评估。例如:

if (!Float.isInfinite(x1.x) || !Float.isInfinite(x1.y))
    circle(x1.x, x1.y, 10);