用opengl写一个立体小球 并且 按键 R变红 B变蓝 G变绿 O变黑 c++
时间: 2024-03-05 07:55:21 浏览: 31
好的,以下是代码示例:
```c++
#include <GL/glut.h>
GLfloat xRotated, yRotated, zRotated;
GLfloat red = 1.0f, green = 1.0f, blue = 1.0f;
void init(void)
{
glClearColor(0.0, 0.0, 0.0, 0.0);
}
void display(void)
{
glMatrixMode(GL_MODELVIEW);
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
glTranslatef(0.0, 0.0, -5.0);
glRotatef(xRotated, 1.0, 0.0, 0.0);
glRotatef(yRotated, 0.0, 1.0, 0.0);
glRotatef(zRotated, 0.0, 0.0, 1.0);
glColor3f(red, green, blue);
glutSolidSphere(1.0, 20, 20);
glFlush();
glutSwapBuffers();
}
void reshape(int x, int y)
{
if (y == 0 || x == 0) return;
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(40.0, (GLdouble)x / (GLdouble)y, 0.5, 20.0);
glMatrixMode(GL_MODELVIEW);
glViewport(0, 0, x, y);
}
void keyboard(unsigned char key, int x, int y)
{
switch (key)
{
case 'r':
case 'R':
red = 1.0f;
green = 0.0f;
blue = 0.0f;
break;
case 'b':
case 'B':
red = 0.0f;
green = 0.0f;
blue = 1.0f;
break;
case 'g':
case 'G':
red = 0.0f;
green = 1.0f;
blue = 0.0f;
break;
case 'o':
case 'O':
red = 0.0f;
green = 0.0f;
blue = 0.0f;
break;
default:
break;
}
glutPostRedisplay();
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize(800, 600);
glutCreateWindow("OpenGL Sphere");
init();
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutKeyboardFunc(keyboard);
glutMainLoop();
return 0;
}
```
这个程序会创建一个带有立体小球的窗口,并且可以按下键盘上的 R、B、G、O 按键来改变小球的颜色。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)