我有一个简单的函数用于设置向量的角度。它有效地获取向量的当前大小(长度),计算角度并将角度从弧度转换为度数。然后,我将角度应用于X和Y,最后乘以向量的原始大小。
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;
}
然而,我不确定如何从向量中获取角度。以下是我的尝试:
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
}
这个尝试除了0或-1之外不会返回任何值。
有什么建议吗?
编辑:
正确的方法:
this.getAngle = function(){
var angle = Math.atan2(this.y, this.x);
var degrees = 180 * angle / Math.PI;
return (360 + Math.round(degrees)) % 360;
}
return (360+Math.round(degrees))%360
- Gavrielthis.getAngle = function(){ var angle = Math.atan2(this.y/this.x); var degrees = 180*angle/Math.PI; return (360+Math.round(degrees))%360; }
?在这种情况下,Javascript会返回Nan。 - Matthew Spence