从方向向量获取角度?

时间:2016-02-08 13:48:01

标签: javascript vector angle direction

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

1 个答案:

答案 0 :(得分:7)

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
}