我画了两点A(x,y)--- B(x,y)之间的一条线现在我有第三个点C(x,y).我想知道如果C位于A和B之间的线上.我想用java语言来做.我找到了几个类似的答案.但是,都有一些问题,没有人是完美的.
MrR*_*ROY 82
if (distance(A, C) + distance(B, C) == distance(A, B))
return true; // C is on the line.
return false; // C is not on the line.
Run Code Online (Sandbox Code Playgroud)
要不就:
return distance(A, C) + distance(B, C) == distance(A, B);
Run Code Online (Sandbox Code Playgroud)
这种方式很简单.如果C位于该AB行上,您将得到以下场景:
A-C------B
Run Code Online (Sandbox Code Playgroud)
并且,无论它在哪一行,dist(AC) + dist(CB) == dist(AB).对于任何其他情况,您有一个描述的三角形和'dist(AC)+ dist(CB)> dist(AB)':
A-----B
\ /
\ /
C
Run Code Online (Sandbox Code Playgroud)
事实上,如果C位于外推线上,这甚至可以工作:
C---A-------B
Run Code Online (Sandbox Code Playgroud)
只要距离保持不合格.距离dist(AB)可以计算为:
___________________________
/ 2 2
V (A.x - B.x) + (A.y - B.y)
Run Code Online (Sandbox Code Playgroud)
请记住浮点运算的固有限制(有限精度).您可能需要选择"足够接近"的测试(例如,小于百万分之一的错误)以确保相等的正确运行.
Sen*_*rJD 11
注意!数学只!

你可以尝试这个公式.把你A(x1, y1)和B(x2, y2)坐标放到公式,然后你会得到类似的东西
y = k*x + b; // k and b - numbers
Run Code Online (Sandbox Code Playgroud)
然后,任何满足这个等式的点都将在你的线上.要检查C(x, y)是否在A(x1, y1)和之间B(x2, y2),请检查:(x1<x<x2 && y1<y<y2) || (x1>x>x2 && y1>y>y2).
例
A(2,3) B(6,5)
Run Code Online (Sandbox Code Playgroud)
线方程:
(y - 3)/(5 - 3) = (x - 2)/(6 - 2)
(y - 3)/2 = (x - 2)/4
4*(y - 3) = 2*(x - 2)
4y - 12 = 2x - 4
4y = 2x + 8
y = 1/2 * x + 2; // equation of line. k = 1/2, b = 2;
Run Code Online (Sandbox Code Playgroud)
让我们检查一下是否C(4,4)在这条线上.
2<4<6 & 3<4<5 // C between A and B
Run Code Online (Sandbox Code Playgroud)
现在把C坐标放到等式中:
4 = 1/2 * 4 + 2
4 = 2 + 2 // equal, C is on line AB
Run Code Online (Sandbox Code Playgroud)
PS:正如@paxdiablo所写,你需要在计算之前检查线是水平还是垂直.检查一下
y1 == y2 || x1 == x2
Run Code Online (Sandbox Code Playgroud)
我相信最简单的是
// is BC inline with AC or visa-versa
public static boolean inLine(Point A, Point B, Point C) {
// if AC is vertical
if (A.x == C.x) return B.x == C.x;
// if AC is horizontal
if (A.y == C.y) return B.y == C.y;
// match the gradients
return (A.x - C.x)*(A.y - C.y) == (C.x - B.x)*(C.y - B.y);
}
Run Code Online (Sandbox Code Playgroud)
您可以通过将x值的差除以y值的差来计算梯度.
注意:如果您在屏幕上绘制C,则会有不同的测试来查看A是否出现在A和B之间的线上.数学假设A,B,C是无限小点.实际上非常小到表示错误.
小智 5
上述答案不必要地复杂。最简单的如下。
如果 (x-x1)/(x2-x1) = (y-y1)/(y2-y1) = alpha(常数),则点 C(x,y) 将位于点 1 和 2 之间的线上。
如果 alpha < 0.0,则 C 在点 1 的外部。
希望这个答案有帮助。
| 归档时间: |
|
| 查看次数: |
40025 次 |
| 最近记录: |