2016-10-02 87 views
0

我想使用2向量的旋轉,但我遇到了兩個問題。首先,載體似乎是向後旋轉,其次,當它們旋轉時,載體在兩個區域之間跳躍。旋轉2向量,向後移動並跳過區域。 C#

這是我使用的旋轉代碼(在一個向量類,具有double xdouble y):

public double radians() 
{ 
    return Math.Atan2(y, x); 
} 

public double len() 
{ 
    return Math.Sqrt(Math.Pow(x, 2) + Math.Pow(y, 2)); 
} 

public vector mul(double d) 
{ 
    return new vector(x * d, y * d); 
} 

public vector div(double d) 
{ 
    return new vector(x/d, y/d); 
} 

public vector unit() 
{ 
    return div(len()); 
} 

public vector rotate(vector v) 
{ 
    double theta = v.radians(); 

    return new vector(
     x * Math.Cos(theta) - y * Math.Sin(theta), 
     x * Math.Cos(theta) + y * Math.Sin(theta)) 
     .unit().mul(len()); // without this, the rotated vector is smaller than the original 
} 

當我使用這些旋轉矢量,它逆時針旋轉,而比順時針我認爲應該。爲了演示,圖像:

original vector in gold, rotated in blue

它也受到了很多比我更認爲它應該旋轉。另一個更難以解釋的問題是,旋轉過程大約有兩分之一的時間內平穩運行,但跳過了另外兩個。我發現的另一個問題是,如果我旋轉矢量的角度很小(在我的測試中,任何過去的(1,10)),旋轉開始強烈,但放慢並最終停止。這在我看來像是C#的double的一個精確問題,但我試圖通過確保旋轉向量的長度不會改變來修復它。

無論如何,如果你能發現一個或所有我的問題的原因,那將不勝感激。

回答

0

我通過更改功能radians()rotate()解決了我的問題。其他功能很好。

radians()固定:

public double radians() 
{ 
    return Math.Atan2(x, y); // swap the x and y 
} 

rotate()固定:

public vector rotate(vector v) 
{ 
    double theta = v.radians(); 

    // use the clockwise rotation matrix: 
    // | cos(theta) sin(theta) | 
    // | -sin(theta) cos(theta) | 
    return new vector(
     x * Math.Cos(theta) + y * Math.Sin(theta), 
     x * -Math.Sin(theta) + y * Math.Cos(theta)); 
} 

這個固定跳躍,向後旋轉時,長度的縮短,和停止。

希望這可以幫助像我這樣的人。