I'm developing some game in order to learn OpenGL.
I'm trying to implement a method to pick objects (e.g. pick axe, gun, etc).
The idea is that this object would lay fixed infront of the camera, even after camera moves or rotates.
What I achieved so far
I can make the object follow me around when I move forward, backward, left, right, up or down, by setting it's position right infront of the camera.
However... when camera rotates / tilts (looking up, down, left, right...) the problems start.
In this case, everything works fine (looking up, down, left, right, tilting right, tilting left... all those operations translates to rotation around x,y,z axes), until I combine several rotations, e.g. rotate 180 degrees backward and then trying to rotate upward (in our language: rotation of 180 degrees over Z axis and then rotation on X axis).
The object starts to rotate around itself in a strange behavior. If I rotate back -180 degress on the Z axis (=looking forward again) and then looking up (rotating around X axis) then the object rotates well.
My game implementation
I have 4 vectors for the camera and 4 vectors for each object: origin, x, y and z (to represent the objects coordinate system).
To move the camera forward, I substract z axis from my current position
Same for other directions.
In order to tilt the camera, for example to the right, I just calculate rotation around Z axis and apply to X,Y axes.
Note: Movement in the world works good, in all directions and angles.
Here's the (the relevant) code I use to position objects in the world. Before drawing them I first put them in their origin (recall: I save an origin and x,y,z axes to all my objects), then do some scale to fit my desired size:
// translate to position
gl.glTranslatef((float)origin.x, (float)origin.y, (float)origin.z);
// scale to size
gl.glScalef((float)size.x, (float)size.y, (float)size.z);
// apply rotation around the object's axes
gl.glRotatef(xrot, (float)x.x, (float)x.y, (float)x.z);
gl.glRotatef(yrot, (float)y.x, (float)y.y, (float)y.z);
gl.glRotatef(zrot, (float)z.x, (float)z.y, (float)z.z);
Edited:
This is how I calculate the angle:
Math.toDegrees(Math.acos(v1.dot(v2))) // dot is a simple dot product