See the image above; basically, I want a simple test to check if a point is within the line se
It's not hard to determine the equations of those perpendicular dotted lines passing through the endpoints of your bold line.
Let the bold line be defined by the points (x1, y1)
and (x2, y2)
. Then, it has a slope
m = (y2 - y1) / (x2 - x1)
So all perpendicular lines will be of the form
y(x) = (-1/m)x + c
We can use that to determine the equations of the perpendicular lines that pass through (x1, y1)
and (x2, y2)
(respectively), which essentially represent the boundary of the region in which all valid points must reside:
ya(x) = (-1/m)x + y1 + x1/m yb(x) = (-1/m)x + y2 + x2/m
So, for an arbitrary point (x*, y*)
, to determine if it lies in the valid region, you can test whether
ya(x*) <= y* <= yb(x*)
(or the reverse if ya(x*)
is larger)
The following should do the trick:
public static boolean check(double x1, double y1, double x2, double y2,
double x, double y) {
if (x1 == x2) { // special case
return y1 < y2 ? (y1 <= y && y <= y2) : (y2 <= y && y <= y1);
}
double m = (y2 - y1) / (x2 - x1);
double r1 = x1 + m * y1;
double r2 = x2 + m * y2;
double r = x + m * y;
return r1 < r2 ? (r1 <= r && r <= r2) : (r2 <= r && r <= r1);
}