2
我有这个简单的功能设置一个向量的角度。它有效地获得矢量的当前量值(长度),计算角度并将角度从弧度转换为度数。然后,我将角度应用于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;
}
但是我不确定如何从Vector中获得(获得)角度。以下是我的尝试:
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;
}
这不会返回准确的角度,我但是发现它被限制成4个devisions 90度?澄清:如果真实角度是90度,它将返回90度,但如果真实角度是95度,则返回-85度? – TheMintyMate
你可以'返回(360 + Math.round(度))%360' – Gavriel
我相信这是行不通的,只有它不符合设置角度时使用的0度?控制台的图像:[链接](http://i.imgur.com/zaao7jE.png?1) – TheMintyMate