Direction Vector To Rotation Matrix

To do what you want to do in your comment, you also need to know the previous orientation of youe Player. Actually, the best thing to do is to store all the data about position and orientation of your player (and almost anything else in a game) into a 4x4 matrix. This is done by "adding" a fourth column and and fourth row to the 3x3 rotation matrix, and use the extra column to store the information about the player position. The math behind this (homogeneous coordinates) is quite simple and very important in both OpenGL and DirectX. I suggest you this great tutorial http://www.opengl-tutorial.org/beginners-tutorials/tutorial-3-matrices/ Now, to rotate your player towards your enemy, using GLM, you can do this:

1) In your player and enemy classes, declare a matrix and 3d vector for the position

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

2) rotate towards enemy with

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) to rotate the enemy towards the player, do

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 

If you want to store everything in the matrix, don't declare the position as a variable but as a function

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

and rotate with

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 

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;
    }
}

Tags:

C++

C

Opengl

Matrix