Reputation: 11
I am having a problem with my code.
//ball joint
glLoadIdentity();
glTranslatef(0.0,0.0,-12.0);
glRotatef(tippangle, 1,0,0);
glRotatef(viewangle, 0,1,0);
glTranslatef(2.5, .6, 0.0);
glPushMatrix();
gluSphere(quad,.25,15,15);
glPopMatrix();
//right arm
glLoadIdentity();
glTranslatef(0.0,0.0,-12.0);
glRotatef(tippangle, 1,0,0);
glRotatef(viewangle, 0,1,0);
glTranslatef(3.2, .55, 0.0);
glRotatef((GLfloat)rightHandAngle, 0.0, 0.0, 1.0);
glScalef(0.5,.12,0.1);
glPushMatrix();
drawBox();
glPopMatrix();
I am attempting to get the rectangle to rotate around the ball joint (its left side) but instead it is rotating at its center. I think the problem lies in the above code.
Upvotes: 1
Views: 133
Reputation: 211106
The sphere is located at (2.5, 0.6):
glTranslatef(2.5, .6, 0.0);
The box is located at (3.2, 0.55):
glTranslatef(3.2, .55, 0.0);
The center of the sphere is the pivot. The vector form the pivot to the origin of the box is:
(3.2, 0.55) - (2.5, 0.6) = (0.75, -0.05)
If you want to rotate an object around a pivot then you've to:
Translate the object in that way that way, that the pivot is on the origin (0, 0, 0). This is the vector form the pivot to the origin of the box (0.75, -0.05).
glTranslatef(0.75, -0.05f, 0.0f);
Rotate the object.
glRotatef((GLfloat)rightHandAngle, 0.0, 0.0, 1.0);
Translate the rectangle in that way that the pivot is back at its original position. This is the negative vector form the pivot to the origin of the box (-0.75, 0.05).
glTranslatef(-0.7, 0.05f, 0.0f);
See also How to use Pivot Point in Transformations
Since operations like glTranslate
and glRotate
define an matrix and multiply the current matrix ba the nes matrix, this operations have to be done in the revers order.
//right arm
glLoadIdentity();
glTranslatef(0.0,0.0,-12.0);
glRotatef(tippangle, 1,0,0);
glRotatef(viewangle, 0,1,0);
glTranslatef(3.2, .55, 0.0);
glTranslatef(-0.7, 0.05f, 0.0f);
glRotatef((GLfloat)rightHandAngle, 0.0, 0.0, 1.0);
glTranslatef(0.75, -0.05f, 0.0f);
glScalef(0.5,.12,0.1);
drawBox();
See also OpenGL translation before and after a rotation.
Upvotes: 1