Hi, I’m new OpenGL and I have a problem with rotations.
I would like to draw a plane and rotate it in about its local axis.
Here is my code. It draws a plane with its local coordinates. I would like to use the keys ‘x’, ‘y’, ‘z’ to rotate about corresponding axis. This doesn’t work correctly. Could you please help me?
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>
GLfloat spin_x = 0;
GLfloat spin_y = 0;
GLfloat spin_z = 0;
void init (void){
glClearColor(0.5,0.5,0.5,0);
glClearDepth(1.0);
glShadeModel(GL_FLAT);
glEnable(GL_DEPTH_TEST);
}
void display(void) {
glClear (GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glColor3f (0.0, 0.0, 0.0);
glLoadIdentity();
gluLookAt(10,10,10,0.0,0.0,0.0,0.0,1.0,0.0);
glRotated(spin_x,1,0,0);
glRotated(spin_y,0,1,0);
glRotated(spin_z,0,0,1);
// Plane
glBegin(GL_POLYGON);
glVertex3f(-1,0,-1);
glVertex3f(-1,0,1);
glVertex3f(1,0,1);
glVertex3f(1,0,-1);
glEnd();
// Coordinates
glColor3f(1,1,1);
glBegin(GL_LINES);
glVertex3f(0,0,0);
glVertex3f(0,0,1);
glVertex3f(0,0,0);
glVertex3f(0,1,0);
glVertex3f(0,0,0);
glVertex3f(1,0,0);
glEnd();
glutSwapBuffers();
}
void reshape(int w, int h){
glViewport(0,0,(GLsizei)w, (GLsizei) h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(30,1,1,200);
glMatrixMode(GL_MODELVIEW);
}
void keyboard(unsigned char key, int x, int y){
switch(key){
case 'x': spin_x +=2;break;
case 'y': spin_y +=2;break;
case 'z': spin_z +=2;break;
}
glutPostRedisplay();
}
int main(int argc, char** argv){
glutInit(&argc, argv);
glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize (500, 500);
glutCreateWindow ("hello");
init();
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutKeyboardFunc(keyboard);
glutMainLoop();
return 0;
}