酷代码 AI
菜单
全部AI  /  热门  /  AI写代码神器
服务商

编写一个C语言粒子樱花代码

# C语言粒子樱花模拟代码 以下是一个使用C语言和SDL2库实现的粒子樱花模拟程序。这个程序会创建多个粉色粒子,模拟樱花花瓣飘落的效果。 ```c #include <SDL2/SDL.h> #include <stdlib.h> #include <math.h> #include <time.h> #define WIDTH 800 #define HEIGHT 600 #define NUM_PARTICLES 150 typedef struct { float x, y; // 位置 float vx, vy; // 速度 float size; // 大小 float life; // 生命周期 Uint8 r, g, b, a; // 颜色(RGBA) } Particle; void initParticle(Particle *p) { p->x = rand() % WIDTH; p->y = 0; p->vx = (float)(rand() % 100 - 50) / 100.0f; p->vy = (float)(rand() % 50 + 50) / 100.0f; p->size = (float)(rand() % 10 + 5); p->life = (float)(rand() % 100 + 100); p->r = 255; p->g = rand() % 55 + 150; // 150-205 p->b = rand() % 55 + 200; // 200-255 p->a = 255; } void updateParticle(Particle *p) { p->x += p->vx; p->y += p->vy; p->vy += 0.02f; // 重力 p->vx += (float)(rand() % 10 - 5) / 100.0f; // 随机风力 // 边界检查 if (p->x < 0) p->x = WIDTH; if (p->x > WIDTH) p->x = 0; p->life -= 1.0f; if (p->life <= 0 || p->y > HEIGHT) { initParticle(p); } } int main(int argc, char *argv[]) { SDL_Init(SDL_INIT_VIDEO); SDL_Window *window = SDL_CreateWindow("樱花飘落", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, WIDTH, HEIGHT, SDL_WINDOW_SHOWN); SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); srand(time(NULL)); Particle particles[NUM_PARTICLES]; for (int i = 0; i < NUM_PARTICLES; i++) { initParticle(&particles[i]); particles[i].y = rand() % HEIGHT; // 随机初始高度 } int running = 1; while (running) { SDL_Event event; while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) { running = 0; } } SDL_SetRenderDrawColor(renderer, 135, 206, 235, 255); // 天空蓝 SDL_RenderClear(renderer); for (int i = 0; i < NUM_PARTICLES; i++) { updateParticle(&particles[i]); SDL_SetRenderDrawColor(renderer, particles[i].r, particles[i].g, particles[i].b, particles[i].a); // 绘制圆形粒子 for (int dy = -particles[i].size; dy <= particles[i].size; dy++) { for (int dx = -particles[i].size; dx <= particles[i].size; dx++) { if (dx*dx + dy*dy <= particles[i].size*particles[i].size) { SDL_RenderDrawPoint(renderer, (int)particles[i].x + dx, (int)particles[i].y + dy); } } } } SDL_RenderPresent(renderer); SDL_Delay(16); // 约60FPS } SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); SDL_Quit(); return 0; } ``` ## 代码说明 1. 这个程序使用SDL2库进行图形渲染 2. 定义了`Particle`结构体来表示每个樱花花瓣的属性 3. `initParticle`函数初始化粒子的位置、速度、大小和颜色 4. `updateParticle`函数更新粒子位置并应用物理效果(重力和随机风力) 5. 主循环中处理粒子更新和渲染 ## 编译和运行 在Linux/macOS上使用以下命令编译: ``` gcc sakura.c -o sakura -lSDL2 -lm ``` 在Windows上需要先安装SDL2开发库,然后使用类似的命令编译。 ## 三条额外需要注意的逻辑点 1. 粒子系统性能优化:当粒子数量增加时,可以考虑使用更高效的渲染方式,如SDL_RenderDrawPoints批量绘制 2. 颜色变化:可以添加随时间变化的颜色过渡,使花瓣颜色更加丰富 3. 交互功能:可以添加鼠标交互,如鼠标移动产生风力影响花瓣飘落方向 [2025-03-31 15:05:28 | AI写代码神器 | 1233点数解答]

相关提问