Question

I have a rather simple question for you.. I feel like I should have found the answer a long time ago but somehow I can't wrap my head around this trivial problem.

Given a vector v = (x,y) , I would like to know it's 'general' orientation. That is either 'Up', 'Down', 'Left' or 'Right'

A vector's general orientation is 'Up' if a Vector's orientation is between 45 and 135 degrees. 'Left' is between 135 and 225 degrees. 'Down' is between 225 and 315 degrees. 'Right' is between 315 and 45 degrees.

I don't really care for the cases where the angle is exactly 45, 135, 225 or 315 degrees.

The catch is, I don't want to use trigonometry. I'm pretty sure there's a simple solution.

I think a solution could split the whole circle in eight. Here's what I have so far.

if(x > 0 && y > x)
    return Up
if(x > 0 && y > 0 && y < x )
    return Right

... etc ...

Basically, I know I could find a solution. I'm more interested in your own approach to this problem.

Thanks !

EDIT : The vector used is not normalized. You can represent any vector using a pair of points. Simply pretend the origin of the vector is (0,0).

Was it helpful?

Solution

There is a way, indeed. All you have to realize is that if abs(y) > abs(x), then the direction is vertical, otherwise the direction is horizontal. If vertical, the sign on y will indicate up/down, otherwise, the sign on x will indicate left/right. So:

if (abs(y) > abs(x)) {
  if (y > 0) up else down
} else {
  if (x > 0) right else left
}

The 45ish angles will always go left or right.

OTHER TIPS

I know you said you wanted to avoid trig, but have you ever used the atan2 function? It's super easy to use for determining the angle of a vector:

double ldAngle = atan2(vector.y, vector.x) * 180 / PI;

Assuming a normalized vector space (Edit: meaning your vector is composed of unit vectors) as you appear to be doing, your approach is spot on and the one most often used for 2d games and animations. I'd verify your truth table, however.

@Daniel's approach is the more elegant IMO.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top