#include float posX = 0.0f, posY = 0.0f; // 方块位置 const float step = 0.05f; // 移动步长 const float size = 0.2f; // 方块半边长 void display() { glClear(GL_COLOR_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); // 绘制方块 glPushMatrix(); glTranslatef(posX, posY, 0.0f); glColor3f(0.0f, 0.8f, 1.0f); // 青色方块 glBegin(GL_QUADS); glVertex2f(-size, -size); glVertex2f( size, -size); glVertex2f( size, size); glVertex2f(-size, size); glEnd(); glPopMatrix(); glutSwapBuffers(); } void reshape(int w, int h) { glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(-1.0, 1.0, -1.0, 1.0); // 坐标系范围 } void keyboard(int key, int x, int y) { // 边界检测(防止移出窗口) switch(key) { case GLUT_KEY_LEFT: if(posX - size > -1.0f) posX -= step; break; case GLUT_KEY_RIGHT: if(posX + size < 1.0f) posX += step; break; case GLUT_KEY_UP: if(posY + size < 1.0f) posY += step; break; case GLUT_KEY_DOWN: if(posY - size > -1.0f) posY -= step; break; } glutPostRedisplay(); } int main(int argc, char** argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB); glutInitWindowSize(600, 600); glutCreateWindow("Keyboard Control"); glutDisplayFunc(display); glutReshapeFunc(reshape); glutSpecialFunc(keyboard); // 注册特殊按键回调 glClearColor(0.2f, 0.2f, 0.2f, 1.0f); // 深灰色背景 glutMainLoop(); return 0; }