python 爱心 粒子代码
时间: 2025-05-12 12:35:02 浏览: 84
### 使用 Python 实现爱心形状的粒子特效
以下是基于 `matplotlib` 的动态立体跳动的心形粒子动画代码示例:
```python
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
# 定义心形参数方程函数
def heart(t, scale=10):
x = scale * 16 * np.sin(t)**3
y = scale * (13 * np.cos(t) - 5 * np.cos(2*t) - 2 * np.cos(3*t) - np.cos(4*t))
return x, y
# 初始化绘图区域
fig, ax = plt.subplots()
ax.set_xlim(-15, 15)
ax.set_ylim(-15, 15)
# 创建粒子数据
num_particles = 200
particles_x = []
particles_y = []
for _ in range(num_particles):
t = np.random.uniform(0, 2 * np.pi)
px, py = heart(t)
particles_x.append(px + np.random.normal(scale=1)) # 添加随机偏移模拟粒子散射
particles_y.append(py + np.random.normal(scale=1))
scatter = ax.scatter(particles_x, particles_y, c='red', s=10)
# 动画更新函数
def update(frame):
global particles_x, particles_y
new_particles_x = []
new_particles_y = []
for i in range(len(particles_x)):
t = frame / 50.0 + np.random.uniform(0, 2 * np.pi)
px, py = heart(t)
# 更新粒子位置并添加随机扰动
new_particles_x.append(px + np.random.normal(scale=1))
new_particles_y.append(py + np.random.normal(scale=1))
scatter.set_offsets(np.c_[new_particles_x, new_particles_y])
particles_x, particles_y = new_particles_x, new_particles_y
return scatter,
# 创建动画对象
ani = FuncAnimation(fig, update, frames=np.arange(0, 200), interval=50)
plt.show()
```
此代码实现了动态跳动的心形粒子效果,其中利用了心形参数方程以及 `FuncAnimation` 来生成动画。
---
#### 关键技术解析
1. **心形参数方程**
心形曲线由以下参数方程定义[^1]:
\[
x = a \cdot 16 \sin^3(t),
\]
\[
y = a \cdot (13\cos(t) - 5\cos(2t) - 2\cos(3t) - \cos(4t)),
\]
其中 \(a\) 是缩放因子,\(t\) 是角度变量。
2. **粒子散射**
颗粒的位置通过加入正态分布噪声来实现自然的效果。这使得每个颗粒不会完全位于理想的心形曲线上,而是围绕其附近波动。
3. **动态效果**
利用 `matplotlib.animation.FuncAnimation` 提供的时间帧机制,在每一帧重新计算所有颗粒的新坐标,并应用轻微的变化以形成心跳般的脉冲感。
---
#### 注意事项
- 如果需要更复杂的视觉效果(如颜色渐变或透明度变化),可以进一步调整 `scatter` 参数中的属性。
- 此代码仅适用于二维平面内的粒子运动;如果希望扩展到三维空间,则需引入其他库(例如 `mpl_toolkits.mplot3d` 或者 Pygame)[^3]。
---
阅读全文
相关推荐


















