I'm working with OpenGL to try to rotate / translate my 3d object : a cow.
The requirement is simple :
- If I toggle key 'r'. The cow spinning around and random axis.
- If I drag the cow with mouse, it translate along its own x axis which means +x directions is for cow's head
- Rotation and translation need not execute at the same time.
- Rotation and translation is done is modeling space.
To implement first requirement, I used timer function like this :
void rotateCow(int value) {
//rotation ended
if (!rotate_flag)
return;
printf("rotateCow\n");
angle = (angle + 5) % 360;
glutPostRedisplay();
glutTimerFunc(30, rotateCow, 1);
}
and for rotation and translation : (some of codes are skipped)
void dragCow() {
glPushMatrix();
//some codes are skipped..
//rotation start
if (rotate_flag == 1) {
rotate_flag = 2;
glutTimerFunc(30, rotateCow, 1);
}
glTranslatef(trans_x, trans_y, trans_z);
glRotatef(angle, rotate_x, rotate_y, rotate_z);
glCallList( cowID ); // Draw cow.
glPopMatrix();
}
void onMouseDrag( int x, int y ) {
y = height - y - 1;
if (trans_flag == DIR_X) {
trans_x = ((x - oldX) / DRAG) + old_trans_x;
}
glutPostRedisplay();
}
If I run as above(rotate and then translate) rotation is as expected.
However, the translation is done in global x-axis not towards head direction of cow.
If I change the order like this :
glRotatef(angle, rotate_x, rotate_y, rotate_z);
glTranslatef(trans_x, trans_y, trans_z);
It shows that translation is as expected(towards head direction of cow).
However, the rotations not works - the rotation-axis made on global x-axis and the cow revolve around that line.
So how can I solve this problem??