javascript - Please show me a more elegant way to do this -
to me, obvious way this: given start point , end point, tell me if end point / down / left / upleft / downright... etc of start point. heres core of 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 num between -pi , 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 better way, more so, how arrived @ way.
i guess key of sorts in order : left = 0 = 90 right = 179 or -179 (down negative mirror of up) down = -90
when doing bounds checking, it's more readable if create function named between(min, val, max);
function between(min, val, max) { return (val > min) && (val < max); }
in addition, can test right/left, , after test down/up.. while appending string. logic cut down 4 if statements.
var final=""; if(/*isup*/) final="up" else if(/*isdown*/) final="down" if(/*isright*/) final+= "right"; else if(/*isleft*/) final += "left";
edit: stated stefan, 57.29578 magical number. didn't realize meant 180/(math.pi)... stated, "optimization" you're making makes code illegible, , performance gain moot.
you should check u/d/l/r x/y position relative origin, not angles.
Comments
Post a Comment