Ray*_*yat 64
我为你解决了方程式:
k = ((y2-y1) * (x3-x1) - (x2-x1) * (y3-y1)) / ((y2-y1)^2 + (x2-x1)^2)
x4 = x3 - k * (y2-y1)
y4 = y3 + k * (x2-x1)
Run Code Online (Sandbox Code Playgroud)
其中^ 2表示平方
Abr*_*xas 10
我同意peter.murray.rust,矢量使解决方案更清晰:
// first convert line to normalized unit vector
double dx = x2 - x1;
double dy = y2 - y1;
double mag = sqrt(dx*dx + dy*dy);
dx /= mag;
dy /= mag;
// translate the point and get the dot product
double lambda = (dx * (x3 - x1)) + (dy * (y3 - y1));
x4 = (dx * lambda) + x1;
y4 = (dy * lambda) + y1;
Run Code Online (Sandbox Code Playgroud)
您经常会发现使用矢量可以使解决方案更清晰......
这是我自己的库中的例程:
public class Line2 {
Real2 from;
Real2 to;
Vector2 vector;
Vector2 unitVector = null;
public Real2 getNearestPointOnLine(Real2 point) {
unitVector = to.subtract(from).getUnitVector();
Vector2 lp = new Vector2(point.subtract(this.from));
double lambda = unitVector.dotProduct(lp);
Real2 vv = unitVector.multiplyBy(lambda);
return from.plus(vv);
}
Run Code Online (Sandbox Code Playgroud)
}
你必须实现Real2(一个点)和Vector2和dotProduct(),但这些应该很简单:
然后代码看起来像:
Point2 p1 = new Point2(x1, y1);
Point2 p2 = new Point2(x2, y2);
Point2 p3 = new Point2(x3, y3);
Line2 line = new Line2(p1, p2);
Point2 p4 = getNearestPointOnLine(p3);
Run Code Online (Sandbox Code Playgroud)
该库(org.xmlcml.euclid)位于:http: //sourceforge.net/projects/cml/
并且有单元测试将执行此方法并向您展示如何使用它.
@Test
public final void testGetNearestPointOnLine() {
Real2 p = l1112.getNearestPointOnLine(new Real2(0., 0.));
Real2Test.assertEquals("point", new Real2(0.4, -0.2), p, 0.0000001);
}
Run Code Online (Sandbox Code Playgroud)
你知道点和斜率,所以新线的等式是:
y-y3=m*(x-x3)
Run Code Online (Sandbox Code Playgroud)
由于线是垂直的,因此斜率是负倒数.你现在有两个方程,可以求解它们的交集.
y-y3=-(1/m)*(x-x3)
y-y1=m*(x-x1)
Run Code Online (Sandbox Code Playgroud)