How do I attach a gun to a camera in OpenGL?

Hello,

I have been working on this program, and I wanted to attach a gun, which will later be able to be fired.

I have the gun following the camera’s position, but it will not rotate along with the camera.

Here is what I have so far:

Code :
gun = glm::translate(gun, glm::vec3(camera.GetPosition().x+ 0.15, camera.GetPosition().y - 0.1, camera.GetPosition().z -0.3));
GLfloat angle = -121.0;

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

What should I add?

The rotate line is so I can get it positioned correctly and the translate is so I can see the gun in the camera.

I just want the gun to stay the way it is no matter how much I rotate the camera.

It does not move with the camera if I look left and right.

Thanks,

RYANISKOOL

I am a little bit too tired at the moment to figure out what is wrong with your code, but the question is how complicated/realistic your game/engine should be.

If you just want to have a gun rendered at your camera position, the easiest way would be to just ignore the world space completely. If you do this, the camera rotation and position irrelevant. Assuming you start with your gun in model space (like in 99% of the cases) you have to rotate the barrel to point into the negative z-direction (after scaling it to the right size). If you are lucky this is already the case. If not, one or two 90 degree rotations should be sufficient, since I can’t imagine that somebody models a gun with its barrel not being aligned to one of the coordinate axes. Result should be that your camera is now somehow located inside the gun and looks in direction of the dangerous end. To fix that, just translate it a little bit to the right and a little bit down. Done… well nearly, you have to multiply the perspective matrix at the end, otherwise your gun would look a little bit strange.

The thing you should keep in mind is that there is no real moving camera.

The solution was the dark matter engine, which doesn’t move the ship through the universe, but instead moves the universe around it at phenomenal speeds and is thereby able to cover incredible distances in a relatively short period of time.
—Futurama Wiki, Dark Matter Engine

Instead of moving the camera, you move all the objects in a way that makes you feel like the camera is moving. This is the world space to camera transformation. So if you want something to be attached to the camera, you just don’t need the world space. You can position your object directly into its final location.

Things get more complicated if you want to do a realistic shooter game. Then you have to attach the camera to the head of your character and the gun location depends on the movement of the limbs. But that is a whole topic of its own.

Greetings