Archie Mejia
Archie Mejia

Reputation: 241

OpenGL failing to use glTranslate and glRotate properly

I'm making a little game here, but there is a small issue with OpenGL. When I translate the camera, and rotate the player's image hoping it would look the same except with a slightly titled texture all went bad. In the example below when I move up the camera moves up but the player moves up according to where the texture is facing (in the example below the texture is moved 50 degrees). What went wrong? How did it happen?

The "Horror Issue" - A Story Of OpenGL

Here is my code:

 glTranslatef(x, y, 0.0f);
 drawMap(); //You don't see the map in the picture
 glRotatef(50.0f, 0.0f, 0.0f, 1.0f);
 drawPlayer();

Thanks!

Upvotes: 0

Views: 395

Answers (1)

glethien
glethien

Reputation: 2471

OpenGL is using a MatrixStack for the modelview matrix which transforms the objects into camera space.

So if you translate without restoring the stack, the translation will also be applied to the player, and the rotation will only be applied to the player. If you do not want the transformation to be applied, reset your stack using glPushMatrix() that implies, that you have used glPushMatrix() before, otherwise you will get a bunch of errors

I recommend that you first read something about the modelview matrix and how to translate/rotate/scale objects using the matrix.

If you want to restore the matrix you can do things like glPushMatrix() to push the current state to the stack and glPopMatrix() to restore the last used state. The stack has always to be cleared at the end, therefore you have to call glPopMatrix() as much often as glPushMatrix() otherwise you will get an error.

There are a lot of very good tutorials out there about the lineare algebra behind OpenGL and how to use it with the built-in methods of OpenGL. [1] And here the accepted answer is very good about the math [2]

[1] http://www.opengl.org/archives/resources/faq/technical/viewing.htm [2] 3D Graphics Processing - How to calculate modelview matrix

Upvotes: 2

Related Questions