Changing the rotation point along with object moving in OpenGL?

1k views Asked by At

I'm trying to build a hammer weapon that can move along with the X-axis and rotate around Z-axis. Right now I have a problem with the hammer. The hammer can rotate around Z-axis on a fixed pivot point, but when I move the hammer to a new position then I rotate the hammer, the hammer still rotates around the old pivot point.

I have tried to add the distance I moved to the old pivot point, but it does not work. How could I solve this problem? Thanks for any helping!

Here is my code:

glPushMatrix();
//the rotation angle of Z-axis
glTranslatef(0.5f,1.0f,-1.0f);    //Back to original point
glRotatef(zr, 0.0f, 0.0f, 1.0f);  //Rotating
glTranslatef(-0.5f,-1.0f,1.0f);   //The rotation piovt point

//build weapon base
//the moving distant on X-axis
glPushMatrix();
glColor3f(1, 0, 0);
glTranslatef(0.5f+xr, 1.0f, -1.0f);
glRotatef(-90.0, 1.0, 0.0, 0.0);
quadratic = gluNewQuadric();
gluCylinder(quadratic, 0.2f, 0.2f, 2.0f, 50, 50);
glPopMatrix();

//build hammer
glPushMatrix();
glTranslatef(0.0+xr, 3.0f, -1.0f);
glRotatef(90.0, 0.0, 1.0, 0.0);
glColor3f(0, 1, 0);
quadratic = gluNewQuadric();
gluCylinder(quadratic, 0.2f, 0.2f, 1.0f, 50, 50);
glPopMatrix();

glPopMatrix();
1

There are 1 answers

4
Rabbid76 On BEST ANSWER

You have to move the pivot, too:

float pivot_x = 0.5f + xr;
glTranslatef(pivot_x, 1.0f, -1.0f);  //Back to original point
glRotatef(zr, 0.0f, 0.0f, 1.0f);     //Rotating
glTranslatef(-pivot_x, -1.0f, 1.0f); //The rotation piovt point