Getting the angle from a direction vector?
Asked Answered
P

1

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;
}
Perky answered 8/2, 2016 at 13:48 Comment(0)
M
20
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
}
Mendy answered 8/2, 2016 at 14:3 Comment(6)
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?Perky
you can return (360+Math.round(degrees))%360Mendy
I believe that does work, only it doesn't align with the 0 degrees used when setting the angle? Image of console: linkPerky
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-360Mendy
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 scenarioPerky
My bad, I didn't see it had updated. Yes this correctly functions now, thank-you.Perky

© 2022 - 2024 — McMap. All rights reserved.