To me, this is the obvious way to do this: given a start point and an end point, tell me if the end point is up / down / left / upleft / downright… etc of the start point. Heres the core of my logic :
function getSector() {
var y = startY - endY;
var x = startX - endX;
var angle = Math.atan2(y,x) * 57.29578;//~57 deg per radian
//atan2(y,x) returns a num between -PI and PI, represents angle in radians
console.log("angle:" + angle);
if( (angle > -22.5) && (angle < 22.5) ) attackDir = "left";
if( (angle > 22.5) && (angle < 67.5) ) attackDir = "upleft";
if( (angle > 67.5) && (angle < 112.5) ) attackDir = "up";
if( (angle > 112.5) && (angle < 157.5) ) attackDir = "upright";
if( (angle > 157.5) && (angle <= 180) ) attackDir = "right";
if( (angle > -179) && (angle <= -157) ) attackDir = "right";
if( (angle > -157) && (angle < -112.5) ) attackDir = "downright";
if( (angle > -112.5) && (angle < -67.5) ) attackDir = "down";
if( (angle > -67.5) && (angle < -22.5) ) attackDir = "downleft";
console.log("attackDir:" + attackDir);
}
I’m interested in seeing a better way, but more so, HOW you arrived at that way.
I guess a key of sorts would be in order :
left = 0
up = 90
right = 179 OR -179 (down is like a negative mirror of up)
down = -90
When doing bounds checking, it’s much more readable if you create a function named Between(min, val, max);
In addition, you can test for right/left, and then after that test for down/up.. while appending to a string. Then your logic is cut down to 4 if statements.
Edit: As stated by Stefan, 57.29578 is a magical number. I didn’t even realize you meant 180/(Math.Pi)… As he also stated, the “optimization” you’re making makes your code just illegible, and the performance gain is moot.
You should always check for u/d/l/r by x/y position relative to an origin, not by angles.