2013-09-01 188 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