12
votes

I have a problem with this openGL code:

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glPushMatrix(); // put current matrix on stack

//glTranslatef(0.0f, 0.0f, 0.0f);   
//glTranslatef(-4*1.5, 0.0, 4*1.5);

glRotatef(rotationAngle, 0.0f, 1.0f, 0.0f); // rotate the robot on its y-axis
glTranslatef(xpos, ypos, zpos);
DrawRobot(xpos, ypos, zpos); // draw the robot
glPopMatrix();

What should I do to make my robot turn around the point at which it is currently situated and not around the origin? I think the problem lies in this snippet.

4

4 Answers

16
votes

Example of rotating an object around its centre along the z-axis:

glPushMatrix();

glTranslatef(250,250,0.0); // 3. Translate to the object's position.

glRotatef(angle,0.0,0.0,1.0); // 2. Rotate the object.

glTranslatef(-250,-250,0.0); // 1. Translate to the origin.

// Draw the object
glPopMatrix();
12
votes

Simply do the rotation after the translation. The order matters.

glTranslatef(xpos, ypos, zpos);
glRotatef(rotationAngle, 0.0f, 1.0f, 0.0f);
3
votes

try rotating after translation:

    glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glPushMatrix(); // put current matrix on stack

//glTranslatef(0.0f, 0.0f, 0.0f);   
//glTranslatef(-4*1.5, 0.0, 4*1.5);

glTranslatef(xpos, ypos, zpos);
glRotatef(rotationAngle, 0.0f, 1.0f, 0.0f); // rotate the robot on its y-axis
DrawRobot(xpos, ypos, zpos); // draw the robot
glPopMatrix();
2
votes

Use this

house();

glTranslatef(x, y, 0.0); // 3. Translate back to original
glRotatef(theta, 0.0, 0.0, 1.0); // 2. Rotate the object around angle
glTranslatef(-m, -n, 0.0); // 1. Move to origin

house();

where m and n are the point on the object around which you want to rotate and x and y are the points around which you want to rotate.