c++3d爱心粒子代码
时间: 2023-10-06 14:14:56 浏览: 689
粒子群算法的源代码.zip C++和matlab
c 3D爱心粒子的代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <GL/glut.h>
#define NUM_PARTICLES 1000
#define MAX_LIFETIME 100
typedef struct {
float x, y, z;
float vx, vy, vz;
float lifetime;
} Particle;
Particle particles[NUM_PARTICLES];
void initParticles() {
for (int i = 0; i < NUM_PARTICLES; i++) {
particles[i].x = 0.0;
particles[i].y = 0.0;
particles[i].z = 0.0;
particles[i].vx = -1.0 + 2.0 * ((float)rand() / RAND_MAX);
particles[i].vy = -1.0 + 2.0 * ((float)rand() / RAND_MAX);
particles[i].vz = -1.0 + 2.0 * ((float)rand() / RAND_MAX);
particles[i].lifetime = (float)(rand() % MAX_LIFETIME);
}
}
void updateParticles() {
for (int i = 0; i < NUM_PARTICLES; i++) {
particles[i].x += particles[i].vx * 0.01;
particles[i].y += particles[i].vy * 0.01;
particles[i].z += particles[i].vz * 0.01;
particles[i].lifetime -= 0.01;
if (particles[i].lifetime <= 0.0) {
particles[i].x = 0.0;
particles[i].y = 0.0;
particles[i].z = 0.0;
particles[i].vx = -1.0 + 2.0 * ((float)rand() / RAND_MAX);
particles[i].vy = -1.0 + 2.0 * ((float)rand() / RAND_MAX);
particles[i].vz = -1.0 + 2.0 * ((float)rand() / RAND_MAX);
particles[i].lifetime = (float)(rand() % MAX_LIFETIME);
}
}
}
void drawParticles() {
for (int i = 0; i < NUM_PARTICLES; i++) {
glPushMatrix();
glTranslatef(particles[i].x, particles[i].y, particles[i].z);
glColor3f(1.0, 0.0, 0.0);
glutSolidSphere(0.1, 10, 10);
glPopMatrix();
}
}
void display() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
drawParticles();
glutSwapBuffers();
}
void reshape(int width, int height) {
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0, (float)width / (float)height, 0.1, 100.0);
}
void idle() {
updateParticles();
glutPostRedisplay();
}
int main(int argc, char** argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(800, 600);
glutCreateWindow("3D Heart Particle");
initParticles();
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutIdleFunc(idle);
glEnable(GL_DEPTH_TEST);
glutMainLoop();
return 0;
}
```
阅读全文