17

如何从方向创建旋转矩阵(单位向量)

我的矩阵是 3x3、列主要和右手

我知道'column1'是对的,'column2'是向上的,'column3'是向前的

但我不能这样做。

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

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

2 回答 2

20
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;
    }
}
于 2013-09-02T13:46:34.420 回答
4

要在评论中做你想做的事情,你还需要知道你之前的播放器方向。实际上,最好的办法是将有关玩家位置和方向的所有数据(以及游戏中的几乎所有其他数据)存储到一个 4x4 矩阵中。这是通过向 3x3 旋转矩阵“添加”第四列和第四行来完成的,并使用额外的列来存储有关玩家位置的信息。这背后的数学(齐次坐标)在 OpenGL 和 DirectX 中都非常简单且非常重要。我建议你这个很棒的教程http://www.opengl-tutorial.org/beginners-tutorials/tutorial-3-matrices/ 现在,使用 GLM 将你的玩家旋转到你的敌人,你可以这样做:

1) 在你的玩家和敌人类中,为位置声明一个矩阵和 3d 向量

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 
于 2013-09-01T16:32:56.507 回答