2
votes

I am trying to calculate if a point resides above or below a line that is defined by two points. For clarification I only need to know if the point is on "this side" or "that side". I realize if the line is perfectly vertical there will be no "above" or "below". I have a line defined by two points (centerX, centerY) and (xprime, yprime). For simplicity centerX, centerY can be converted to (0,0). I want to determine if (mouseX, mouseY) is above or below that line.

I have tried to use this formula but it is not giving me the results I expected.

var position = Math.sin((xprime -centerX) * (mouseY - centerY) - (yprime - centerY) * (mouseX - prime));

The values for position seem to oscillate randomly from positive to negative as mouseX,mouseY values rotate around the line. I was under the impression the sign would change one time from positive to negative as the mouse position (mouseX,mouseY) crossed over the line. Values above the line would be positive, and values below would be negative.

I am using this code in conjunction with a formula to determine the angle of deflection from the original click. But I am not able to determine if the mouse is now above the initial click, or below. (again please excuse "above" and "below")

2

2 Answers

3
votes

Simple solution exploiting cross product properties.

dx = xprime - centerX
dy = yprime - centerY
mx = mouseX - centerX
my = mouseY - centerY
cross = dx * my - dy * mx    //zero means point on line
below = (cross > 0)          //mouse is "at the right hand" of the directed line   
if dx <> 0 then              // check for vertical line
  if dy/dx < 0 then         //negative slope, invert result
    below = not below
1
votes

I'll try to give you general solution.

How to check if exact point is above or below line function:

Just imagine, we have line f(x) = 4x + 2. We need check, if point (x1, y1) below or above the line, we need to calculate f(x1) and compare it with y1.

if f(x1) > y1 it means, that (x1, y1) below the line.

if f(x1) < y1 means point (x1, y1) above the line.

if f(x1) = y1 - point on a line.

You can see on plot:

enter image description here

All line functions looks like f(x) = k * x + b, so, you need know k and b constants to know exact line function.

How to get line function by two points:

Imagine points A (x_a, y_a) and B (x_b, y_b) and we want to get line function, we need to solve system of two equations:

y_a = k * x_a + b

y_b = k * x_b + b

That is very easy. After you will know k and b and after you can check if point below or above AB line