Search code examples
javagwtvectorjava-canvas

How to check if point is inside the rectangle around a diagonal line?


First of all: I know I can calc the distance from a point to a line to check if the point was on the line. This is what I do for detecting clicks (with an offset) on a line.

But before that, I want to apply a general check around the diagonal line. The line itself with Start and End point defines a rectangular area:

Pstart(sx, sy), Pend(ex, ey).

I can use boundary check to determine if the Point(px, py) was inside that rectangle:

sx <= px && ex >= px && sy <= px && ey >= py

But this only applies if the line goes from top left to bottom right. If it goes a different direction I have to modify the algorithm. How could I use my formula above regardless of the line direction?

How can I get the formula to respect the direction accordingly?


Solution

  • Just compare for Math.min(sx, ex) <= px <= Math.max(sx, ex) and likewise for the y dimension.