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
point1andpoint2are different, first you check whether the point lies on the line. For that you simply need a “cross-product” of vectorspoint1 -> currPointandpoint1 -> point2.Your point lies on the line if and only if
crossis equal to zero.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
xcoordinates, if the line is “more horizontal than vertical”, orycoordinates otherwiseNote 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
crossthough.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.