用C++写个会动的爱心
时间: 2024-02-09 14:09:26 浏览: 63
这里是用C++和图形库OpenGL实现一个简单的会动的爱心的示例代码。具体实现方式如下:
```c++
#include <GL/glut.h>
#include <math.h>
// 设置窗口大小
const GLint W = 800, H = 600;
// 设置心形大小
const GLfloat a = 1.5, b = 1.5;
// 设置步长
const GLfloat delta = 0.01;
// 初始化函数
void init()
{
glClearColor(0.0, 0.0, 0.0, 0.0); // 设置背景为黑色
glMatrixMode(GL_PROJECTION); // 设置投影模式
glLoadIdentity();
gluOrtho2D(-W / 2, W / 2, -H / 2, H / 2); // 设置正交投影区域
}
// 画出一个点
void drawPoint(GLfloat x, GLfloat y)
{
glBegin(GL_POINTS);
glVertex2f(x, y);
glEnd();
}
// 画出一个心形
void drawHeart()
{
GLfloat x, y, theta;
for (theta = 0.0; theta <= 2 * M_PI; theta += delta) {
x = a * pow(sin(theta), 3);
y = b * pow(cos(theta), 3);
drawPoint(x, y);
}
}
// 显示函数
void display()
{
glClear(GL_COLOR_BUFFER_BIT); // 清屏
glColor3f(1.0, 0.0, 0.0); // 设置颜色为红色
glPointSize(2.0); // 设置点的大小
drawHeart(); // 画出心形
glutSwapBuffers(); // 切换缓冲区
}
// 定时器函数
void timer(int value)
{
static GLfloat x = 0.0, y = 0.0;
static GLfloat dx = 0.02, dy = 0.02;
x += dx;
y += dy;
if (x > W / 2 || x < -W / 2) {
dx = -dx;
}
if (y > H / 2 || y < -H / 2) {
dy = -dy;
}
glMatrixMode(GL_MODELVIEW); // 设置模型视图模式
glLoadIdentity();
glTranslatef(x, y, 0.0); // 平移
glutPostRedisplay(); // 刷新屏幕
glutTimerFunc(50, timer, 0); // 重新注册定时器
}
// 主函数
int main(int argc, char** argv)
{
glutInit(&argc, argv); // 初始化glut库
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB); // 设置显示模式
glutInitWindowSize(W, H); // 设置窗口大小
glutInitWindowPosition(100, 100); // 设置窗口位置
glutCreateWindow("Heart"); // 创建窗口
init(); // 初始化
glutDisplayFunc(display); // 注册显示回调函数
glutTimerFunc(50, timer, 0); // 注册定时器函数
glutMainLoop(); // 进入事件循环
return 0;
}
```
运行上述代码后,会显示出一个会动的爱心,爱心会在窗口中上下左右移动。
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)