Search code examples
c++copenglrotationtranslate-animation

Why does this OpenGL rotation also translate my object?


I'm trying to rotate an object (an arrow) which has it's default position as pointing to the right. I've been looking around and I'm using the glLoadIdentity() and glPushMatrix() and glPopMatrix() as a way to only rotate the object in my glBegin function and not the whole scene:

glLoadIdentity();
glPushMatrix();
glRotatef(5, 0.0f, 0.0f, 1.0f);
glBegin(GL_TRIANGLE_FAN);
    glColor3f(1.0f, 0.0f, 1.0f);
    glVertex2f(xx2-0.01, yy2);
    glVertex2f(xx2-0.06, yy2+0.03);
    glVertex2f(xx2-0.06, yy2-0.03);
glEnd();
glPopMatrix();

However, it also translates my arrow, instead of only rotating it. Do I need to translate the offset back to it's original position? Or am I doing something wrong?

SOLVED:

glLoadIdentity();
glPushMatrix();
glTranslatef(xx2, yy2, 0);
glRotatef(45, 0.0f, 0.0f, 1.0f);
glTranslatef(-xx2, -yy2, 0);
glBegin(GL_TRIANGLE_FAN);
    glColor3f(1.0f, 0.0f, 1.0f);
    glVertex2f(xx2-0.01, yy2);
    glVertex2f(xx2-0.06, yy2+0.03);
    glVertex2f(xx2-0.06, yy2-0.03);
glEnd();
glPopMatrix();

Need to translate back to center (0, 0, 0), apply the rotation and then back to it's original position (xx2, yy2, 0)


Solution

  • All rotations are around the origin.

    So yes, if you want to rotate around some other point, you must translate from that point to the origin, rotate, and then translate back again.