I am trying to check the location of a point(px, py) on 2D graph in relation to a line segment (lx1, ly1) (lx2, ly2), using logic of North South East West directions. The logic I have implemented is to draw a perpendicular on the line segment from the point.
if perpendicular is on line that means its south.
If point on right side means its East.
If point on left side means West.
If perpendicular is away from line in forward direction will mean North.
If perpendicular is away from line in backward direction will mean South.
My problem is that this logic looks good on paper, but its getting really hard to decide whether its a NW, NE, SW or SE case. Can anyone suggest me how to compute this logic?? I am using C++, but algorithm in any language will be a great help.
I am using end point of line segment to calculate North South East West relation.
Cheers
Best Answer
delta_x = x2 - x1
delta_y = y2 - y1
distance = sqrt (delta_x^2 + delta_y^2)
tan (theta) = delta_y / delta_x
theta = arctan (delta_y / delta_x)
;; but don't divide by zero!theta
by180/PI
to get degreesThe degrees are counter-clockwise from the positive side of the x-axis. Eventually you'll need to do a small amount of algebra to reorient the degrees so that 0 is up (instead of to the right) and run clockwise. But before that:
A problem is that
arctan (1 / -1)
is the same asarctan (-1 / 1)
. I.e., you'll get-PI/4
radians or -45 degrees, for both upper left (needs 180 degree offset) and lower right (ok as is). You'll have to do tests on the sign ofdelta_y
vs.delta_x
to see if the result ofarctan
needs to be adjusted.Before you code your solution, be sure to code tests as well to make sure the functions you are calling produce expected values.