Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
100
rated 0 times [  104] [ 4]  / answers: 1 / hits: 19092  / 8 Years ago, mon, february 8, 2016, 12:00:00

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;
}

More From » vector

 Answers
1
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
}

[#63397] Friday, February 5, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jayden

Total Points: 108
Total Questions: 109
Total Answers: 107

Location: Kenya
Member since Mon, Jun 14, 2021
3 Years ago
;