I was looking all over the internet for any information on how to get a gun to stay with a camera as done in FPS games.

I am using OpenGL and GLSL to carry this out. I knew a way of how to do this in earlier OpenGL versions, but I could never figure it out in the newer versions.

The type of camera that I am trying to get is something similar to this

With the view matrix and everything else, I should be able to figure out the movement of the hand and the shooting.

Here is some of the code that I have so far:

//Copyright(c) 2019 Ryan Hall All Rights Reserved
//I do not permit any of this code to be used elsewhere by anyone else except me for commercial purposes.
//The gun has two defining variables: one that actually creates the gun and another that moves it around in object space

weaponOfChoice = glm::translate(weaponOfChoice, glm::vec3(camera.GetPosition().x+ 0.15, camera.GetPosition().y - 0.15, camera.GetPosition().z -0.3));

weaponOfChoice = glm::rotate(gun, angle, glm::vec3(0.0f, 1.0f, 0.0f));  

weaponOfChoice = glm::scale(gun, glm::vec3(0.005f, 0.005f, 0.005f));

         glUniformMatrix4fv(glGetUniformLocation(shader.Program, "gun"), 1, GL_FALSE, glm::value_ptr(weaponOfChoice));

I have spent quite some time working on how to fix the code so that it will render the gun correctly and have not been able to find any great sources online that will help solve my problem.

How could I do this?

Do I need an identity matrix as used by me in older versions of OpenGL?

If so, how do I create a mimicking function of glLoadIdentity() that will help me with this problem?



  • 2
    \$\begingroup\$ Guns in FPS games are typically not rendered in world-space by snapping them to the player's position. Instead they have their own render pass that is done in screen-space. The dpeth buffer is also cleared to avoid clipping the gun through scenery. \$\endgroup\$ – Quentin Feb 27 '19 at 9:50
  • \$\begingroup\$ How could I do this? \$\endgroup\$ – rjhwinner03 Mar 1 '19 at 20:15
  • \$\begingroup\$ @Quentin that sounds like it would be worth writing up as an answer. You've got some folks willing to upvote that information already. All it needs are a few tips about how to do this in code. \$\endgroup\$ – DMGregory Mar 3 '19 at 14:07
  • \$\begingroup\$ @DMGregory Unfortunately I've not used OpenGL recently so the details are fuzzy to me... \$\endgroup\$ – Quentin Mar 4 '19 at 8:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.