Search code examples
c++openglmatrixcameraglm-math

OpenGL Make Object Stick to Camera


In my adventures to better understand what exactly is going on with matrices and vertex math with OpenGL, I wanted to see if I could get an object to "stick" in front of my "camera". I have been playing with this for a couple of days now and feel like I'm getting close.

So far I have managed to get the object to follow the camera's movement, except for it's rotation (I just can't seem to figure out this front vector). To create the new position of the object I have the following code:

glm::mat4 mtx_trans = glm::mat4(1.0f);
mtx_trans = glm::translate(mtx_trans, camera->getPosition() + camera->getFront());

glm::vec4 cubePosVec4 = glm::vec4(0.0f, 0.0f, -3.0f, 1.0);
cubePosVec4 = mtx_trans * cubePosVec4;

cubePositions[9] = glm::vec3(cubePosVec4.x, cubePosVec4.y, cubePosVec4.z);

Where camera->getPosition() obtains the camera's current position vector and camera->getFront() obtains the camera's current front vector.

As mentioned I'm in the process of learning what all is going on here, so it's possible I'm going about this all wrong...In which case how should I go about "locking" an object a certain distance away from the camera?


Solution

  • If the object should always be at the same position in relation to the camera, then you've to skip the transformation by the view matrix.

    Note, the view matrix transforms from world space to view space. If the object should always be placed in front of the camera, then the object has not to be placed in the world, it has to be placed in the view. Therefore, the "view" matrix for the object is the identity matrix.

    So the common model view transformation for the object in your case is a translation of the object in along the z axis in negative direction. The translation has to be negative, because the z axis points out of the view (in view space):

    glm::mat4 mtx_trans = glm::mat4(1.0f);
    mtx_trans = glm::translate(mtx_trans, glm::vec3(0.0f, 0.0f, -3.0f));