本文介绍了如何检查一个点是否位于另外两个点之间的线上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将如何编写这个函数?任何例子表示赞赏

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
}

推荐答案

假设 point1point2 不同,首先检查点是否在直线上.为此,您只需要向量 point1 -> 的叉积";currPointpoint1 ->点2.

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;

当且仅当 cross 等于 0 时,您的观点才在线.

Your point lies on the line if and only if cross is equal to zero.

if (cross != 0)
  return false;

现在,您知道该点确实位于线上,是时候检查它是否位于原始点之间.这可以通过比较 x 坐标来轻松完成,如果线条水平多于垂直",或者 y 坐标否则

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;

请注意,如果输入数据是整数,则上述算法如果完全是整数,即它不需要对整数输入进行浮点计算.不过在计算 cross 时要小心潜在的溢出.

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.

这篇关于如何检查一个点是否位于另外两个点之间的线上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 01:13