# 粒子系统
PixiJS 的 ParticleContainer 可以高效管理大量 Sprite 粒子。
# ParticleContainer
普通 Container 在管理上千个对象时性能会下降,ParticleContainer 针对大量粒子做了优化:
import { ParticleContainer, Sprite } from 'pixi.js';
// 创建粒子容器,指定最大容量
const particles = new ParticleContainer(10000, {
scale: true,
position: true,
rotation: true,
alpha: true,
});
app.stage.addChild(particles);
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
# 创建粒子效果 {#create-particles}
function createParticles(count) {
for (let i = 0; i < count; i++) {
const particle = Sprite.from('dot.png');
particle.x = Math.random() * app.screen.width;
particle.y = Math.random() * app.screen.height;
particle.scale.set(Math.random() * 0.5 + 0.5);
particle.alpha = Math.random() * 0.8 + 0.2;
// 存储自定义速度属性
particle.vx = (Math.random() - 0.5) * 2;
particle.vy = (Math.random() - 0.5) * 2;
particles.addChild(particle);
}
}
// 更新粒子位置
app.ticker.add(() => {
for (const p of particles.children) {
p.x += p.vx;
p.y += p.vy;
// 边界回弹
if (p.x < 0 || p.x > app.screen.width) p.vx *= -1;
if (p.y < 0 || p.y > app.screen.height) p.vy *= -1;
}
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# 跟随鼠标的粒子 {#mouse-follow-particles}
let mouseX = 0;
let mouseY = 0;
app.stage.eventMode = 'static';
app.stage.on('pointermove', (e) => {
mouseX = e.global.x;
mouseY = e.global.y;
});
app.ticker.add(() => {
for (const p of particles.children) {
// 粒子向鼠标位置靠近
p.x += (mouseX - p.x) * 0.02;
p.y += (mouseY - p.y) * 0.02;
}
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 效率对比 {#performance-comparison}
| 粒子数 | Container (FPS) | ParticleContainer (FPS) |
|---|---|---|
| 1000 | 60 | 60 |
| 5000 | 45 | 60 |
| 10000 | 22 | 55 |
| 50000 | 5 | 30 |
# 在线 Demo {#online-demo}
← 动画与 Ticker 滤镜效果 →