2016-02-08 179 views
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
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 
} 
+0

這不會返回準確的角度,我但是發現它被限制成4個devisions 90度?澄清:如果真實角度是90度,它將返回90度,但如果真實角度是95度,則返回-85度? – TheMintyMate

+0

你可以'返回(360 + Math.round(度))%360' – Gavriel

+0

我相信這是行不通的,只有它不符合設置角度時使用的0度?控制檯的圖像:[鏈接](http://i.imgur.com/zaao7jE.png?1) – TheMintyMate