I try to rotate a cube with keyboard but I can’t. The first rotation works correctly but the second rotation is broken.I understand why, but I can’t figure out how to fix it. First glRotatef is for rotation on x.It works but the second glRotote that is for rotation on y is not working like first one.
Think like I want to rotate on the camera axis.But when you click Left or Right,the cube turns on its own y axis
NOTE.:: You need to press the arrows when it first work ///////////
#include <GL/glut.h>
#include <iostream>
using namespace std;
GLfloat rx = 0, ry = 0;
void drawCube(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_DEPTH_TEST);
glBegin(GL_QUADS);
glColor3f(0.0, 1.0, 0.0);
glVertex3f(1.0, 1.0, 1.0);
glVertex3f(-1.0, 1.0, 1.0);
glVertex3f(-1.0, 1.0, -1.0);
glVertex3f(1.0, 1.0, -1.0);
glColor3f(1.0, 0.0, 0.0);
glVertex3f(1.0, -1.0, 1.0);
glVertex3f(-1.0, -1.0, 1.0);
glVertex3f(-1.0, -1.0, -1.0);
glVertex3f(1.0, -1.0, -1.0);
glColor3f(1.0, 1.0, 0.0);
glVertex3f(1.0, 1.0, -1.0);
glVertex3f(-1.0, 1.0, -1.0);
glVertex3f(-1.0, -1.0, -1.0);
glVertex3f(1.0, -1.0, -1.0);
glColor3f(0.0, 0.0, 1.0);
glVertex3f(1.0, 1.0, 1.0);
glVertex3f(1.0, 1.0, -1.0);
glVertex3f(1.0, -1.0, -1.0);
glVertex3f(1.0, -1.0, 1.0);
glColor3f(1.0, 0.5, 0.0);
glVertex3f(-1.0, 1.0, 1.0);
glVertex3f(-1.0, 1.0, -1.0);
glVertex3f(-1.0, -1.0, -1.0);
glVertex3f(-1.0, -1.0, 1.0);
glColor3f(1.0, 0.5, 1.0);
glVertex3f(1.0, 1.0, 1.0);
glVertex3f(-1.0, 1.0, 1.0);
glVertex3f(-1.0, -1.0, 1.0);
glVertex3f(1.0, -1.0, 1.0);
glEnd();
glutSwapBuffers();
}
void arrows(int key, int x, int y)
{
glLoadIdentity();
gluLookAt(0,0,5,0,0,0,0,1,0);
switch (key) {
case GLUT_KEY_LEFT: ry += 5;
glRotatef(rx, 1, 0, 0); // Up and down arrow keys 'tip' view.
glRotatef(ry, 0, 1, 0); // Right/left arrow keys 'turn' view.
break;
case GLUT_KEY_RIGHT: ry -= 5;
glRotatef(rx, 1, 0, 0); // Up and down arrow keys 'tip' view.
glRotatef(ry, 0, 1, 0); // Right/left arrow keys 'turn' view.
break;
case GLUT_KEY_UP: rx += 5;
glRotatef(rx, 1, 0, 0); // Up and down arrow keys 'tip' view.
glRotatef(ry, 0, 1, 0); // Right/left arrow keys 'turn' view.
break;
case GLUT_KEY_DOWN: rx -= 5;
glRotatef(rx, 1, 0, 0); // Up and down arrow keys 'tip' view.
glRotatef(ry, 0, 1, 0); // Right/left arrow keys 'turn' view.
break;
}
cout << rx << " " << ry << "
";
drawCube();
}
int main(int argc, char **argv){
glutInit(&argc, argv);
glutInitWindowSize(640, 480);
glutInitWindowPosition(300, 150);
glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE);
glutCreateWindow("");
glutSpecialFunc(arrows);
glClearColor(1.0, 1.0, 1.0, 1.0);
glMatrixMode(GL_PROJECTION);
gluPerspective(100, 1.5, 1, 10);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glutMainLoop();
return 0;
}