object staying in front of camera, please help

Hello there everybody! Has anybody here managed to get a solid object constantly floating in front of the camera view? For example, a gun like in Fps’s?

Based on some tutorials I followed, I have managed to create a small 3D world, where I can run around using keys and the mouse for direction. I have made a thin, long gun barrel out of a quadratic cylindar, and given it a nice texture. I am just struggling to get it behave now! It can rotate when I rotate, it moves on the X, Y and Z plane when I do, but I just cant get it to sit there pointing and moving in the right direction simultaneoulsy! This is a snippet of code which I am having the problem with:

glTranslatef(xtrans, ytrans, ztrans); // Translate The Scene Based On my Position


glTranslatef(-xtrans, -(ytrans + 0.12f), -ztrans); //Here I am moving the gun to the same location as me. (adding 0.12f to the Y axis to let the gun float at a certain height.)

glRotatef(-sceneroty,0,1.0f,0); //To rotate gun based on ‘sceneroty’ which is calculated from mouse coords

glBindTexture(GL_TEXTURE_2D, texture[4]); //add the gun texture

gluCylinder(quadratic,0.02f,0.02f,1.0f,40,40); //The Cylinder for my gun.


Now when I run this, the barrel does follow me around, and it also rotates correctly along with my rotation. The problem is that when I start, it is pointed behind me!! So if I try translate it in front of my (by adding some amount to the Z axis) the barrel no longer rotates around me. AAAARGH!

Are there any algorithms out there I havent found yet which cover this sort of thing? Surely loads of people must have made a FPS shooter here who can help me.
Any ideas would be greatly appreciated, Thanks!

Draw the gun first infront of the camera then transform the camera to the player position and draw the level. (or the other way round and use a glLoadIdentity call)

Hi, thanks for reply but I have just tried that, and all sorts goes wrong. It is so annoying, because I am so close, and yet so far. My gun is moving perfectly, except it is pointing behind me i.e. I can only see it if I move the mouse so that I am looking behind me, upside down. There it is, following me, and even rotating to point where I am am looking. But it’s behind me.

If any one is willing to help, I will gladly send them all my code. It is only very small at the moment (one cpp file). I have been trying to solve this for days now, Please help!

Each frame…

  1. Save your matrix (glPushMatrix)
  2. Draw your gun. You might have to translate it -z to be able to see it in front of the camera.
  3. Restore your matrix (glPopMatrix).
  4. Perform your camera transforms (gluLookAt)
  5. Draw the rest of the world.