从方向向量中获取角度?

9

我有一个简单的函数用于设置向量的角度。它有效地获取向量的当前大小(长度),计算角度并将角度从弧度转换为度数。然后,我将角度应用于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;
}
1个回答

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

这确实返回了准确的角度,但我发现它仅限于90度的4个部分?为了澄清:如果实际角度为90度,则返回90度,但如果实际角度为95度,则返回-85度? - Matthew Spence
你可以使用以下代码:return (360+Math.round(degrees))%360 - Gavriel
我相信那个代码是可以正常工作的,只是它没有与设定角度时使用的0度对齐。控制台图像:链接 - Matthew Spence
奇怪,我认为使用atan2更好,至少在0-180之间是可以的,然后用%360现在就可以在0-360之间了。 - Gavriel
你是指像这样吗?this.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
我的错,我没有看到它已经更新了。是的,现在它可以正常运行了,谢谢你。 - Matthew Spence

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接