2013-09-01 190 views
6

如何創建旋轉矩陣從方向(單位矢量)方向向量旋轉矩陣

我矩陣是3×3,列爲主,和右側

我知道「列1」是正確的,「列2」是up and'column3'is forward

但是我不能這樣做。

//3x3, Right Hand 
struct Mat3x3 
{ 
    Vec3 column1; 
    Vec3 column2; 
    Vec3 column3; 

    void makeRotationDir(const Vec3& direction) 
    { 
     //:((
    } 
} 
+1

對於旋轉矩陣,您需要一個方向矢量(例如軸)**和**一個角度。給出一個方向你在說什麼輪換? – 6502

+0

我想這樣做: Vec3 dirToEnemy =(Enemy.Position - Player.Position).normalize(); Player.Matrix.makeRotationDir(dir); Player.Attack(); – UfnCod3r

+0

@ 6502:不,對於旋轉矩陣,你也可以使用三個向量(x,y,z) – SigTerm

回答

5

感謝所有旋轉。 解決。

struct Mat3x3 
{ 
    Vec3 column1; 
    Vec3 column2; 
    Vec3 column3; 

    void makeRotationDir(const Vec3& direction, const Vec3& up = Vec3(0,1,0)) 
    { 
     Vec3 xaxis = Vec3::Cross(up, direction); 
     xaxis.normalizeFast(); 

     Vec3 yaxis = Vec3::Cross(direction, xaxis); 
     yaxis.normalizeFast(); 

     column1.x = xaxis.x; 
     column1.y = yaxis.x; 
     column1.z = direction.x; 

     column2.x = xaxis.y; 
     column2.y = yaxis.y; 
     column2.z = direction.y; 

     column3.x = xaxis.z; 
     column3.y = yaxis.z; 
     column3.z = direction.z; 
    } 
} 
+0

那麼如果方向對應向上不旋轉? –

2

要做你想在你的評論中做的事情,你還需要知道你的玩家以前的方向。實際上,最好的辦法是將所有關於玩家的位置和方向(以及遊戲中的其他任何東西)的數據存儲爲4x4矩陣。這是通過將第四列和第四行「添加」到3x3旋轉矩陣來完成的,並使用額外的列來存儲關於玩家位置的信息。背後的數學(齊次座標)非常簡單,在OpenGL和DirectX中都非常重要。我建議你這個偉大的教程http://www.opengl-tutorial.org/beginners-tutorials/tutorial-3-matrices/ 現在,您的播放器向你的敵人旋轉,使用GLM,你可以這樣做:

1)在您的播放器和敵對階級,宣告矩陣和三維矢量位置

glm::mat4 matrix; 
glm::vec3 position; 

2)向敵人旋轉與

player.matrix = glm::LookAt(
player.position, // position of the player 
enemy.position, // position of the enemy 
vec3(0.0f,1.0f,0.0f));  // the up direction 

3)旋轉朝着玩家的敵人,做

enemy.matrix = glm::LookAt(
enemy.position, // position of the player 
player.position, // position of the enemy 
vec3(0.0f,1.0f,0.0f));  // the up direction 

如果你想存儲矩陣中的一切,不申報的位置作爲一個變量,但作爲一個功能

vec3 position(){ 
    return vec3(matrix[3][0],matrix[3][1],matrix[3][2]) 
} 

player.matrix = glm::LookAt(
player.position(), // position of the player 
enemy.position(), // position of the enemy 
vec3(0.0f,1.0f,0.0f));  // the up direction