c语言实现烟花特效
时间: 2023-07-13 21:22:12 浏览: 77
实现烟花特效需要用到图形库,比如OpenGL或者SDL等。以下是一个基于SDL图形库的烟花特效的C语言实现代码示例:
```
#include <SDL2/SDL.h>
#include <stdlib.h>
#include <time.h>
// 烟花粒子结构体
typedef struct {
double x, y; // 粒子位置
double vx, vy; // 粒子速度
double ax, ay; // 粒子加速度
double radius; // 粒子半径
double life; // 粒子寿命
double max_life; // 粒子最大寿命
} Particle;
// 随机数生成函数
double rand_double(double min, double max) {
return ((double)rand() / RAND_MAX) * (max - min) + min;
}
// 烟花爆炸函数
void explode(Particle particles[], int x, int y) {
int i;
for (i = 0; i < 100; i++) {
particles[i].x = x;
particles[i].y = y;
particles[i].vx = rand_double(-200, 200);
particles[i].vy = rand_double(-200, 200);
particles[i].ax = 0;
particles[i].ay = 50;
particles[i].radius = rand_double(1, 3);
particles[i].life = 0;
particles[i].max_life = rand_double(0.5, 1.5);
}
}
int main() {
SDL_Window* window;
SDL_Renderer* renderer;
Particle particles[100];
int running = 1;
int i;
// 初始化SDL
SDL_Init(SDL_INIT_VIDEO);
window = SDL_CreateWindow("Fireworks", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, SDL_WINDOW_SHOWN);
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
// 随机数种子初始化
srand(time(NULL));
while (running) {
SDL_Event event;
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) {
running = 0;
}
if (event.type == SDL_MOUSEBUTTONDOWN) {
explode(particles, event.button.x, event.button.y);
}
}
// 清屏
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
SDL_RenderClear(renderer);
// 更新粒子状态
for (i = 0; i < 100; i++) {
particles[i].vx += particles[i].ax * 0.01;
particles[i].vy += particles[i].ay * 0.01;
particles[i].x += particles[i].vx * 0.01;
particles[i].y += particles[i].vy * 0.01;
particles[i].life += 0.01;
if (particles[i].life > particles[i].max_life) {
particles[i].radius = 0;
}
}
// 绘制粒子
for (i = 0; i < 100; i++) {
SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255 * (1 - particles[i].life / particles[i].max_life));
SDL_Rect rect = { particles[i].x - particles[i].radius, particles[i].y - particles[i].radius, particles[i].radius * 2, particles[i].radius * 2 };
SDL_RenderFillRect(renderer, &rect);
}
// 更新屏幕
SDL_RenderPresent(renderer);
}
// 释放资源
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
```
该程序使用SDL库实现烟花特效,鼠标点击窗口即可触发烟花爆炸效果。在爆炸时,程序会生成100个粒子,并为每个粒子随机设置速度、加速度、大小和寿命等属性。程序主循环中,每帧更新粒子状态并重新绘制屏幕,从而实现烟花特效。