javascript - Converting between -180-180 to 0-360 -


i have function returns angle -180 180 , need 0 360. formula convert angle?

here's want:

    0/360  270      90      180 

here's have:

         -90  -180/180        0           90 

any appreciated, working on html/javascript game.

there number of ways can done while preserving equivalent angle, assumptions values.

if sure values in range [-180,180), can use following:

var x = math.random()*360-180;  // generate random angle in range [-180, 180) var y = x < 0 ? x+360 : x;      // normalize in range [0, 360) 

if you're doing lot, branch operation may result in poor behavior (though maybe not in javascript ... you'd need profile it). so, it's better without branching operation. can using modulus (%) operator.

var x = math.random()*360-180;  // generate random angle in range [-180, 180) var y = (x + 360) % 360;        // normalize in range [0, 360) 

if cannot guarantee original value in range [-180, 180) can divide out number of turns. like

var x = getangle();   // angle, potentially outside [-180, 180) var y = x - 360 * math.floor(x/360);  // normalizes in range [0, 360) 

some care need taken large absolute values of x due way floating point numbers represented (which understand javascript uses, when integer values work well)

edit: noticed changing consider 0 angle (above rather right). in case, need add 90 degrees rotate 0 correct position. in case, first code segment becomes:

var x = math.random()*360-180;  // generate random angle in range [-180, 180) var y = x < -90 ? x+450 : x+90;    // normalize in range [0, 360) 

the next 1 becomes amadan indicated.

var x = math.random()*360-180;  // generate random angle in range [-180, 180) var y = (x + 450) % 360;        // normalize in range [0, 360) 

and last 1 becomes

var x = getangle();   // angle, potentially outside [-180, 180) var y = (x+90) - 360 * math.floor((x+90)/360);  // normalizes in range [0, 360) 

Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -