6

I need to figure out how to calculate on which side of a line a point is. I'm searching a really fast and simple collision algorithm because I just need to know on what side a object is to define a collision state.

Just like:

if(x > line.x)
    return EnumSide.LEFT;

But the line needs to be diagonally. Any ideas?

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
bitQUAKE
  • 473
  • 1
  • 8
  • 19
  • 2
    possible duplicate of [Determine which side of a line a point lies](http://stackoverflow.com/questions/3461453/determine-which-side-of-a-line-a-point-lies) – sushain97 Mar 26 '14 at 17:31
  • Evaluate the function at the questionable x and determine if the y value is greater or less than the function's – clcto Mar 26 '14 at 17:31
  • Possible duplicate of [How to tell whether a point is to the right or left side of a line](https://stackoverflow.com/questions/1560492/how-to-tell-whether-a-point-is-to-the-right-or-left-side-of-a-line) – StayOnTarget Jun 22 '18 at 18:25

1 Answers1

12

Given a directed line from point p0(x0, y0) to p1(x1, y1), you can use the following condition to decide whether a point p2(x2, y2) is on the left of the line, on the right, or on the same line:

value = (x1 - x0)(y2 - y0) - (x2 - x0)(y1 - y0)

if value > 0, p2 is on the left side of the line.
if value = 0, p2 is on the same line.
if value < 0, p2 is on the right side of the line.

And here's a figure to explain it all:

Which side of line is the point?

Aman Agnihotri
  • 2,973
  • 1
  • 18
  • 22
  • 1
    The explanation is given in terms of determinants and cross products in this answer and its comments: http://stackoverflow.com/a/1560510/284529 – David Doria Apr 27 '16 at 17:53
  • I think you made a mistake. (x2 - x0)(y1 - y0) should be (y1 - y0)(y2 - y1) – John Demetriou Apr 27 '17 at 10:07
  • 1
    @JohnDemetriou I think what you are thinking is it should be (y1 - y0)(x2 - x0) which of course is what he put just reversed. I doubt it should be (y1-y0)(y2-y1), x needs to be involved. – Lupus Ossorum Sep 25 '18 at 03:04