Home Ask Login Register

Developers Planet

Your answer is one click away!

TheMintyMate February 2016

Getting the angle from a direction vector?

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.multiply(l);  //original magnitude

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?


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;


Gavriel February 2016

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

Post Status

Asked in February 2016
Viewed 3,698 times
Voted 6
Answered 1 times


Leave an answer

Quote of the day: live life