given is a Cartesian coordinate system and a point(x,y) within this system. For example a point p has the coordinates (-12,2):
|
|
p |
|
------------------+------------------>
|
|
|
|
Now I need a function/algorithm that calculates the opposite “direction” (north, east, south, west) from the coordinate system’s center (0,0) based on the given point. In our example the best opposite direction to choose would be EAST, following the X-axis to the right.
However, in some situations within my application not all directions are an option to choose, in such a case the next-best direction has to be chosen. In our example, if EAST would not be possible, then the next-best direction would be SOUTH (then NORTH, then WEST).
I could solve this with some if-statements, but that does not seem to be very elegant.
Any other (better) ideas?
Use the dot product of your vector
(x, y)with the unit vectors along the four directionsThe smallest number corresponds the direction you want. Then the second smallest, and so on.
This works for any directions not just E, W, S and N – you just need to pick unit vectors along the desired directions and compare the dot products