2017-08-31 80 views
1

我一直試圖圍繞任意軸工作得到矩陣旋轉,我想我很接近但是我有一個bug。我對3D旋轉比較陌生,對發生的事情有基本的瞭解。矩陣圍繞任意軸旋轉問題

public static Matrix4D Rotate(Vector3D u, Vector3D v) 
{ 
    double angle = Acos(u.Dot(v)); 
    Vector3D axis = u.Cross(v); 

    double c = Cos(angle); 
    double s = Sin(angle); 
    double t = 1 - c; 

    return new Matrix4D(new double [,] 
    { 
     { c + Pow(axis.X, 2) * t, axis.X * axis.Y * t -axis.Z * s, axis.X * axis.Z * t + axis.Y * s, 0 }, 
     { axis.Y * axis.X * t + axis.Z * s, c + Pow(axis.Y, 2) * t, axis.Y * axis.Z * t - axis.X * s, 0 }, 
     { axis.Z * axis.X * t - axis.Y * s, axis.Z * axis.Y * t + axis.X * s, c + Pow(axis.Z, 2) * t, 0 }, 
     { 0, 0, 0, 1 } 
    }); 
} 

上面的代碼是矩陣旋轉的算法。當我用單位向量測試算法時,我得到以下結果:

Matrix4D rotationMatrix = Matrix4D.Rotate(new Vector3D(1, 0, 0), new Vector3D(0, 0, 1)); 

Vector4D vectorToRotate = new Vector4D(1,0,0,0); 

Vector4D result = rotationMatrix * vectorToRotate; 

//Result 
X = 0.0000000000000000612; 
Y = 0; 
Z = 1; 
Length = 1; 

隨着90度的旋轉,我發現它幾乎完美的工作。現在,讓我們來看看一個45度旋轉:

Matrix4D rotationMatrix = Matrix4D.Rotate(new Vector3D(1, 0, 0), new Vector3D(1, 0, 1).Normalize()); 

Vector4D vectorToRotate = new Vector4D(1,0,0,0); 

Vector4D result = rotationMatrix * vectorToRotate; 

//Result 
X = .70710678118654746; 
Y = 0; 
Z = .5; 
Length = 0.8660254037844386; 

當我們乘坐ATAN(0.5/0.707),我們發現,我們有35.28度的旋轉,而不是45度旋轉。矢量的長度也從1變爲.866。有沒有人有任何提示我做錯了什麼?

+1

讓我補充一點,讓使用'ACOS(u.Dot(V))'是不是很好的角度,因爲如果兩個向量是幾乎垂直的結果是不穩定。使用'Atan2((u.Cross(v))。Magnitude,u.Dot(v))'代替。 – ja72

回答

4

你的矩陣代碼看起來是正確的,但你需要正常化太(只是因爲uv歸一化並不意味着u cross v也是)。

(我也建議使用一個簡單的乘法,而不是Pow,性能和精度的原因,但這是次要的,而不是你的問題的來源)

1

只是給後人,這是我使用的代碼對於這個確切的事情。我總是推薦使用Atan2(dy,dx)而不是Acos(dx),因爲它在接近90°的角度更穩定。

public static class Rotations 
{ 
    public static Matrix4x4 FromTwoVectors(Vector3 u, Vector3 v) 
    { 
     Vector3 n = Vector3.Cross(u, v); 
     double sin = n.Length(); // use |u×v| = |u||v| SIN(θ) 
     double cos = Vector3.Dot(u, v); // use u·v = |u||v| COS(θ) 

     // what if u×v=0, or u·v=0. The full quadrant arctan below is fine with it. 
     double angle = Atan2(sin, cos); 
     n = Vector3.Normalize(n); 

     return FromAxisAngle(n, angle); 
    } 
    public static Matrix4x4 FromAxisAngle(Vector3 n, double angle) 
    { 
     // Asssume `n` is normalized 
     double x = n.X, y = n.Y, z = n.Z; 
     double sin = Sin(angle); 
     double vcos = 1.0-Cos(angle); 

     return new Matrix4x4(
      1.0-vcos*(y*y+z*z), vcos*x*y-sin*z, vcos*x*z+sin*y, 0, 
      vcos*x*y+sin*z, 1.0-vcos*(x*x+z*z), vcos*y*z-sin*x, 0, 
      vcos*x*z-sin*y, vcos*y*z+sin*x, 1.0-vcos*(x*x+y*y), 0, 
      0, 0, 0, 1.0); 
    } 
} 

代碼爲C#