通过鼠标控制正方体的旋转方向,通过键盘控制正方体的移动
#include <GL/glut.h>
#include<stdlib.h>
GLint b;
GLint aa[3];
GLint u;
GLint xfirst;
GLint yfirst;
GLint xsecond;
GLint ysecond;
GLint x1;
GLint y1;
bool mousedown=0;
void display()
{
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glEnable(GL_DEPTH_TEST);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
//gluLookAt(0,0.5,1,0,0,0,0,1,0);
//glRotatef(b,0,1,0);
glRotatef(ysecond,1,0,0);
glRotatef(xsecond,0,1,0);
glTranslatef(x1,y1,0);
//glColor3f(0,0,0);
glutSolidCube(3);
glutSwapBuffers();
}
void cube()
{
b+=2;
if(b>=360)b-=360;
glutPostRedisplay();
}
void mouse(int button,int state,int x,int y)
{
if(button==GLUT_LEFT_BUTTON&&state==GLUT_DOWN)
{
mousedown=1;
xfirst=x-xsecond;
yfirst=y-ysecond;
}
glutPostRedisplay();
}
void mouseMotion(int x,int y)
{
if(mousedown==1)
{ysecond=y-yfirst;
xsecond=x-xfirst;}
glutPostRedisplay();
}
void key(unsigned char key,int x,int y)
{
if(key=='k')
exit(0);
}
void SpecialKey(int key,GLint x,GLint y)
{
switch(key)
{
case GLUT_KEY_UP:y1+=1;break;
case GLUT_KEY_DOWN:y1-=1;break;
}
glutPostRedisplay();
}
void mm(int value)
{
switch(value)
{
case 1:glColor3f(1,0,0); break;
case 2:glColor3f(0,1,0); break;
case 3:glColor3f(0,0,1); break;
case 4:glColor3f(1,1,0); break;
}
glutPostRedisplay();
}
void time(int value)
{
aa[u]+=2;
if(aa[u]>=360)aa[u]-=360;
glutPostRedisplay();
glutTimerFunc(20,time,1);
}
void reshape(int w,int h)
{
glViewport(0,0,w,h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-10.0,10.0,-10.0,10.0,-10.0,10.0);
}
void init()
{
glClearColor(1.0,1.0,1.0,1.0);
GLfloat light0_ambient[]= { 0.2, 0.2, 0.2, 1.0 };
GLfloat light0_diffuse[]= { 1.0, 1.0, 1.0, 1.0};
GLfloat light0_specular[] = { 1.0, 0, 0, 1.0 };
GLfloat light0_position[] = { 1.0, 1.0, 1.0, 0.0 };
glLightfv(GL_LIGHT0, GL_AMBIENT, light0_ambient);
glLightfv(GL_LIGHT0, GL_DIFFUSE, light0_diffuse);
glLightfv(GL_LIGHT0, GL_SPECULAR,light0_specular);
glLightfv(GL_LIGHT0, GL_POSITION,light0_position);
glEnable(GL_LIGHTING);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_LIGHT0);
}
int main(int argc,char** argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB);
glutCreateWindow("simple");
glutReshapeFunc(reshape);
glutDisplayFunc(display);
// glutIdleFunc(cube);
//glutTimerFunc(20,time,1);
glutMouseFunc(mouse);
glutKeyboardFunc(key);
glutSpecialFunc(SpecialKey);
glutMotionFunc(mouseMotion);
GLint menu;
menu=glutCreateMenu(mm);
glutAddMenuEntry("Red",1);
glutAddMenuEntry("Green",2);
glutAddMenuEntry("Blue",3);
glutAddMenuEntry("Yellow",4);
glutAttachMenu(GLUT_RIGHT_BUTTON);
init();
glutMainLoop();
return(true);
}