Reputation: 366
I am trying to rotate an image around it's center. here is the code:
glPushMatrix();
glTranslatef(-x, -y, 0);
glRotatef(10, 0, 0, 1);
glTranslatef(x, y, 0);
glBindTexture(GL_TEXTURE_2D, img);
glBegin(GL_QUADS);
glTexCoord2i(0, 0);
glVertex2i(x, y);
glTexCoord2i(1, 0);
glVertex2i(x+width, y);
glTexCoord2i(1, 1);
glVertex2i(x+width, y+height);
glTexCoord2i(0, 1);
glVertex2i(x, y + height);
glEnd();
glPopMatrix();
I read everywhere to translate my image to the center of rotation then rotate and translate it back. But when i tried doing it step by step I found out that when I translate and then rotate it moves the center of rotation along with the image, so it rotates around a point that is offscreen on the same distance from the image as the initial point of rotation from the initial image before translation. Can anyone tell me why this happens or how to fix it?
Upvotes: 1
Views: 980
Reputation: 22165
Matrix-Operations and thus glTranslatef/glRotatef are applied in reversed order. So when your rotation center is c=(x,y), you have to translate along -c first, then rotate and then translate along c.
In your case, you have to exchange the two translate lines to the following:
glTranslatef(x, y, 0); //Translate back
glRotatef(10, 0, 0, 1); //Rotate
glTranslatef(-x, -y, 0); //Translate first along -c
Upvotes: 2