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.
JavaScript
x
9
1
this.setAngle = function(degree){
2
var l = this.length(); //magnitude of vector
3
var angle = degree*Math.PI/180; //degress converted to radians
4
this.x=Math.cos(angle);
5
this.y=Math.sin(angle);
6
this.multiply(l); //original magnitude
7
return;
8
}
9
However I am unsure how to obtain (get) an angle from a Vector. Below is my attempt:
JavaScript
1
6
1
this.getAngle = function(){
2
var angle = Math.atan(this.y/this.x); //radians
3
var degrees = angle/(180*Math.PI); //degrees
4
return Math.floor(degrees); //round number, avoid decimal fragments
5
}
6
This attempt doesn’t return any value except 0 or -1.
Any suggestions?
Edit:
Correct method:
JavaScript
1
6
1
this.getAngle = function(){
2
var angle = Math.atan2(this.y, this.x);
3
var degrees = 180 * angle / Math.PI;
4
return (360 + Math.round(degrees)) % 360;
5
}
6
Advertisement
Answer
JavaScript
1
7
1
this.getAngle = function(){
2
var angle = Math.atan2(this.y, this.x); //radians
3
// you need to devide by PI, and MULTIPLY by 180:
4
var degrees = 180*angle/Math.PI; //degrees
5
return (360+Math.round(degrees))%360; //round number, avoid decimal fragments
6
}
7