2014-10-17 18 views
0

我有以下幾點:的Javascript矢量輪作

function Vec2(x, y) { 
this.x = x; 
this.y = y; 
} 

Vec2.prototype.rotate = function(d) { 
var x = this.x; 
var y = this.y; 
this.x = x * Math.cos(d) + y * Math.sin(d); 
this.y = y * Math.cos(d) - x * Math.sin(d); 
} 

var v = new Vec2(0, 1); 

而經過:

v.rotate(90); 

的載體應該是1,0,但是這將返回0.8939966636005579, - (或-1,0?) 0.4480736161291702。

這是爲什麼?

+0

'd'應該先轉換成弧度(不是deg)? – 2014-10-17 01:30:41

+0

我試着用我的radInDeg()函數旋轉位,但它仍然有錯誤的值,加上我90%確定這個方程使用度。 – 2014-10-17 01:33:25

+0

傳入的參數是'90deg',您必須將該90deg轉換爲相應的弧度值('Math.PI/2'),不知道如何使用'radInDeg' – 2014-10-17 01:36:33

回答

1

製作toRad功能,然後在'd'上使用它。

function toRad(Value) { 
    return Value * Math.PI/180; 
} 

Vec2.prototype.rotate = function(d) { 
d = toRad(d); 
var x = this.x; 
var y = this.y; 
this.x = x * Math.cos(d) - y * Math.sin(d); 
this.y = y * Math.cos(d) + x * Math.sin(d); 
} 

你的函數也在使用我發佈的函數中的錯誤方程。

+0

是的,那是我的radInDeg(),但它沒有幫助。 – 2014-10-17 01:35:28

+0

現在返回:1,6.123233995736766e-17 – 2014-10-17 01:41:33

+0

@ user3786755看起來像是四捨五入的問題,該值幾乎接近'0'。 – 2014-10-17 01:44:12