使用OpenGL 实现一个实心小球沿三角形均速运动代码
时间: 2023-12-22 18:04:11 浏览: 29
以下是使用OpenGL实现一个实心小球沿三角形均速运动的代码,使用C++编写:
```c++
#include <GL/glut.h>
// 窗口大小
int windowWidth = 800;
int windowHeight = 600;
// 相机位置
GLfloat camera[] = { 0.0f, 0.0f, 10.0f };
// 三角形顶点坐标
GLfloat triangle[][3] = {
{ 0.0f, 1.0f, 0.0f },
{ -1.0f, -1.0f, 0.0f },
{ 1.0f, -1.0f, 0.0f }
};
// 小球位置
GLfloat ball[] = { 0.0f, 0.0f, 0.0f };
// 小球速度
GLfloat velocity[] = { 0.01f, -0.01f, 0.0f };
// 绘制三角形
void drawTriangle() {
glBegin(GL_TRIANGLES);
glColor3f(1.0f, 0.0f, 0.0f);
glVertex3fv(triangle[0]);
glColor3f(0.0f, 1.0f, 0.0f);
glVertex3fv(triangle[1]);
glColor3f(0.0f, 0.0f, 1.0f);
glVertex3fv(triangle[2]);
glEnd();
}
// 绘制小球
void drawBall() {
glPushMatrix();
glColor3f(1.0f, 1.0f, 1.0f);
glTranslatef(ball[0], ball[1], ball[2]);
glutSolidSphere(0.1f, 20, 20);
glPopMatrix();
}
// 更新小球位置
void updateBallPosition() {
ball[0] += velocity[0];
ball[1] += velocity[1];
// 碰到边界反弹
if (ball[0] <= -1.0f || ball[0] >= 1.0f) {
velocity[0] = -velocity[0];
}
if (ball[1] <= -1.0f || ball[1] >= 1.0f) {
velocity[1] = -velocity[1];
}
}
// 绘制回调函数
void display() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
gluLookAt(camera[0], camera[1], camera[2], 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f);
drawTriangle();
drawBall();
updateBallPosition();
glutSwapBuffers();
}
// 窗口大小改变回调函数
void reshape(int width, int height) {
windowWidth = width;
windowHeight = height;
glViewport(0, 0, windowWidth, windowHeight);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0f, (GLfloat)windowWidth / (GLfloat)windowHeight, 0.1f, 100.0f);
glMatrixMode(GL_MODELVIEW);
}
// 定时器回调函数,每隔20ms调用一次
void timer(int value) {
glutPostRedisplay();
glutTimerFunc(20, timer, 0);
}
int main(int argc, char** argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(windowWidth, windowHeight);
glutCreateWindow("OpenGL");
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glEnable(GL_DEPTH_TEST);
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutTimerFunc(20, timer, 0);
glutMainLoop();
return 0;
}
```
在代码中,我们使用OpenGL绘制一个三角形和一个实心小球,并让小球沿三角形均速运动。小球的位置由 `ball` 数组表示,速度由 `velocity` 数组表示。在 `updateBallPosition` 函数中,我们更新小球的位置,并判断小球是否碰到了边界,如果碰到了就反弹。在 `display` 函数中,我们绘制三角形和小球,并调用 `updateBallPosition` 函数更新小球位置。在 `timer` 函数中,我们使用定时器每隔20ms调用一次 `display` 函数,让小球动起来。