使用OpenGL 实现一个实心小球沿矩形均速运动代码
时间: 2024-05-11 20:14:43 浏览: 12
以下是一个使用OpenGL实现实心小球沿矩形均速运动的示例代码:
```
#include <GL/glut.h>
#include <math.h>
float ballX = 0.0f; // 实心小球的横坐标
float ballY = 0.0f; // 实心小球的纵坐标
float ballRadius = 0.2f; // 实心小球的半径
float ballSpeed = 0.01f; // 实心小球的速度
float rectWidth = 2.0f; // 矩形的宽度
float rectHeight = 2.0f; // 矩形的高度
void drawBall() {
glColor3f(1.0f, 0.0f, 0.0f); // 设置颜色为红色
glBegin(GL_TRIANGLE_FAN);
glVertex2f(ballX, ballY); // 中心点
int numSegments = 100;
float angle;
for (int i = 0; i <= numSegments; i++) {
angle = i * 2.0f * M_PI / numSegments;
glVertex2f(ballX + (ballRadius * cos(angle)), ballY + (ballRadius * sin(angle)));
}
glEnd();
}
void drawRect() {
glColor3f(0.0f, 0.0f, 1.0f); // 设置颜色为蓝色
glBegin(GL_QUADS);
glVertex2f(-rectWidth/2, -rectHeight/2); // 左下角
glVertex2f(rectWidth/2, -rectHeight/2); // 右下角
glVertex2f(rectWidth/2, rectHeight/2); // 右上角
glVertex2f(-rectWidth/2, rectHeight/2); // 左上角
glEnd();
}
void display() {
glClearColor(1.0f, 1.0f, 1.0f, 1.0f); // 设置背景为白色
glClear(GL_COLOR_BUFFER_BIT);
drawBall();
drawRect();
glutSwapBuffers();
}
void update(int value) {
// 计算实心小球下一帧的位置
ballX += ballSpeed;
if (ballX > rectWidth/2 - ballRadius || ballX < -rectWidth/2 + ballRadius) {
ballSpeed *= -1;
}
glutPostRedisplay();
glutTimerFunc(10, update, 0);
}
int main(int argc, char** argv) {
glutInit(&argc, argv);
glutInitWindowSize(500, 500);
glutInitWindowPosition(100, 100);
glutCreateWindow("Solid Ball");
glutDisplayFunc(display);
glutTimerFunc(10, update, 0);
glutMainLoop();
return 0;
}
```
在这个示例代码中,我们定义了一个实心小球和一个矩形,并让实心小球沿着矩形均速运动。在 `drawBall()` 函数中,我们使用 `GL_TRIANGLE_FAN` 来绘制实心小球,使用 `glVertex2f()` 来设置每个顶点的坐标。在 `drawRect()` 函数中,我们使用 `GL_QUADS` 来绘制矩形,同样使用 `glVertex2f()` 来设置每个顶点的坐标。在 `display()` 函数中,我们清空颜色缓冲区并绘制实心小球和矩形。在 `update()` 函数中,我们计算实心小球下一帧的位置,并检查是否碰到了矩形的边界,如果是,则改变小球的运动方向。最后,我们使用 `glutTimerFunc()` 来定时更新实心小球的位置,并使用 `glutMainLoop()` 进入主循环。
相关推荐
![](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)