如何检查是否一个点位于其他2点之间的线路 [英] How to check if a point lies on a line between 2 other points
问题描述
我怎么会写这样的功能?任何示例AP preciated
函数isPointBetweenPoints(currPoint,点1,点2):布尔{
VAR currX = currPoint.x;
VAR咖喱= currPoint.y;
VAR P1X = point1.x;
VAR P1Y = point1.y;
VAR P2X = point2.x;
VAR P2Y = point2.y;
//这里我卡
}
假设点1
和点2
是不同的,首先检查点是否在就行了。对于你只需要一个跨产品的载体点1 - > currPoint
和点1 - >点2
。
DXC = currPoint.x - point1.x;
DYC = currPoint.y - point1.y;
DXL = point2.x - point1.x;
DYL = point2.y - point1.y;
跨= DXC * DYL - DYC * DXL;
您点位于上线当且仅当交叉
等于零。
如果(穿越!= 0)
返回false;
现在,你知道点做就行了谎言,现在是时候来检查它是否处于的在的原始点。这可以通过比较轻松完成X
坐标,如果线路不是垂直多横,或是
坐标否则
IF(ABS(DXL)> = ABS(DYL))
返回DXL> 0?
point1.x< = currPoint.x和放大器;&安培; currPoint.x< = point2.x:
point2.x< = currPoint.x和放大器;&安培; currPoint.x< = point1.x;
其他
返回DYL> 0?
point1.y< = currPoint.y和放大器;&安培; currPoint.y< = point2.y:
point2.y< = currPoint.y和放大器;&安培; currPoint.y< = point1.y;
请注意,上述算法,如果完全积分如果输入数据是一体的,即它不需要浮点计算为整数输入。计算时,当心潜在溢出交叉
虽然。
P.S。这种算法是绝对precise,这意味着它会拒绝谎言非常接近线的点,但不就行了precisely。有时,这不是我们所需要的。但是,这是一个不同的故事。
How would I write this function? Any examples appreciated
function isPointBetweenPoints(currPoint, point1, point2):Boolean {
var currX = currPoint.x;
var currY = currPoint.y;
var p1X = point1.x;
var p1y = point1.y;
var p2X = point2.x;
var p2y = point2.y;
//here I'm stuck
}
Assuming that point1
and point2
are different, first you check whether the point lies on the line. For that you simply need a "cross-product" of vectors point1 -> currPoint
and point1 -> point2
.
dxc = currPoint.x - point1.x;
dyc = currPoint.y - point1.y;
dxl = point2.x - point1.x;
dyl = point2.y - point1.y;
cross = dxc * dyl - dyc * dxl;
Your point lies on the line if and only if cross
is equal to zero.
if (cross != 0)
return false;
Now, as you know that the point does lie on the line, it is time to check whether it lies between the original points. This can be easily done by comparing the x
coordinates, if the line is "more horizontal than vertical", or y
coordinates otherwise
if (abs(dxl) >= abs(dyl))
return dxl > 0 ?
point1.x <= currPoint.x && currPoint.x <= point2.x :
point2.x <= currPoint.x && currPoint.x <= point1.x;
else
return dyl > 0 ?
point1.y <= currPoint.y && currPoint.y <= point2.y :
point2.y <= currPoint.y && currPoint.y <= point1.y;
Note that the above algorithm if entirely integral if the input data is integral, i.e. it requires no floating-point calculations for integer input. Beware of potential overflow when calculating cross
though.
P.S. This algorithm is absolutely precise, meaning that it will reject points that lie very close to the line but not precisely on the line. Sometimes this is not what's needed. But that's a different story.
这篇关于如何检查是否一个点位于其他2点之间的线路的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!