9

I have this simple function to set an angle for a vector. It effectively gets the vector's current magnitude (length), calulates the angle and converts the angle from radians to degrees. Then I apply the angle to X and Y, lastly multiplying the vector by it's original magnitude.

this.setAngle = function(degree){
    var l = this.length();  //magnitude of vector
    var angle = degree*Math.PI/180; //degress converted to radians
    this.x=Math.cos(angle);
    this.y=Math.sin(angle);
    this.multiply(l);  //original magnitude
    return;
}

However I am unsure how to obtain (get) an angle from a Vector. Below is my attempt:

this.getAngle = function(){
    var angle = Math.atan(this.y/this.x);   //radians
    var degrees = angle/(180*Math.PI);  //degrees
    return Math.floor(degrees); //round number, avoid decimal fragments
}

This attempt doesn't return any value except 0 or -1.

Any suggestions?

Edit:

Correct method:

this.getAngle = function(){
    var angle = Math.atan2(this.y, this.x);
    var degrees = 180 * angle / Math.PI;
    return (360 + Math.round(degrees)) % 360;
}
Matthew Spence
  • 986
  • 2
  • 9
  • 27

1 Answers1

18
this.getAngle = function(){
    var angle = Math.atan2(this.y, this.x);   //radians
    // you need to devide by PI, and MULTIPLY by 180:
    var degrees = 180*angle/Math.PI;  //degrees
    return (360+Math.round(degrees))%360; //round number, avoid decimal fragments
}
Gavriel
  • 18,880
  • 12
  • 68
  • 105
  • This does return an accurate angle, I am finding however that it is limited into 4 devisions of 90 degrees? To clarify: if the real angle is 90 degrees, it will return 90 degrees, but if the real angle is 95 degrees, it returns -85 degrees? – Matthew Spence Feb 08 '16 at 14:34
  • you can `return (360+Math.round(degrees))%360` – Gavriel Feb 08 '16 at 14:36
  • I believe that does work, only it doesn't align with the 0 degrees used when setting the angle? Image of console: [link](http://i.imgur.com/zaao7jE.png?1) – Matthew Spence Feb 08 '16 at 14:47
  • Strange, I think with atan2 it's better, at least from 0-180 it's ok then, and with the %360 now it's ok 0-360 – Gavriel Feb 08 '16 at 15:04
  • Do you mean like this? `this.getAngle = function(){ var angle = Math.atan2(this.y/this.x); var degrees = 180*angle/Math.PI; return (360+Math.round(degrees))%360; }` ? Javascript returns Nan in this scenario – Matthew Spence Feb 08 '16 at 15:12
  • My bad, I didn't see it had updated. Yes this correctly functions now, thank-you. – Matthew Spence Feb 08 '16 at 15:15