粒子容器
🌐 Particle Container
PixiJS v8 通过 ParticleContainer 和 Particle 类引入了高性能粒子系统。该系统设计用于渲染大量轻量级视觉效果——如火花、气泡、兔子或爆炸——通过去除所有非必要的开销来提供原始速度。
🌐 PixiJS v8 introduces a high-performance particle system via the ParticleContainer and Particle classes. Designed for rendering vast numbers of lightweight visuals—like sparks, bubbles, bunnies, or explosions—this system provides raw speed by stripping away all non-essential overhead.
粒子 API 稳定但实验性。其接口可能会在未来的 PixiJS 版本中发生变化。我们欢迎反馈以帮助指导其开发。
import { ParticleContainer, Particle, Texture } from 'pixi.js';
const texture = Texture.from('bunny.png');
const container = new ParticleContainer({
dynamicProperties: {
position: true, // default
vertex: false,
rotation: false,
color: false,
},
});
for (let i = 0; i < 100000; i++) {
const particle = new Particle({
texture,
x: Math.random() * 800,
y: Math.random() * 600,
});
container.addParticle(particle);
}
app.stage.addChild(container);
为什么使用 ParticleContainer?
🌐 Why Use ParticleContainer?
- 极致性能:以高帧率渲染数十万甚至数百万颗粒子。
- 轻量级设计:粒子比
Sprite更高效,缺少诸如子元素、事件或滤镜等额外功能。 - 细粒度控制:通过声明哪些属性是动态的(每帧更新)或静态的(设置一次)来优化渲染。
性能提示:静态 vs 动态
🌐 Performance Tip: Static vs. Dynamic
- 动态属性 每一帧都会上传到 GPU。
- 静态属性 仅在调用
update()时上传。
明确声明你的需求:
🌐 Declare your needs explicitly:
const container = new ParticleContainer({
dynamicProperties: {
position: true,
rotation: true,
vertex: false,
color: false,
},
});
如果你稍后修改静态属性或粒子列表,则必须调用:
🌐 If you later modify a static property or the particle list, you must call:
container.update();
限制和 API 差异
🌐 Limitations and API Differences
ParticleContainer 旨在追求速度和简便。因此,它不支持完整的 Container API:
❌ 不可用:
🌐 ❌ Not Available:
addChild(),removeChild()getChildAt(),setChildIndex()swapChildren(),reparentChild()
✅ 可使用替代:
🌐 ✅ Use Instead:
addParticle(particle)removeParticle(particle)removeParticles(beginIndex, endIndex)addParticleAt(particle, index)removeParticleAt(index)
这些方法在 .particleChildren 数组上运行,并正确维护内部 GPU 缓冲区。
🌐 These methods operate on the .particleChildren array and maintain the internal GPU buffers correctly.
创建粒子
🌐 Creating a Particle
Particle 支持关键显示属性,并且比 Sprite 高效得多。
🌐 A Particle supports key display properties, and is far more efficient than Sprite.
粒子示例
🌐 Particle Example
const particle = new Particle({
texture: Texture.from('spark.png'),
x: 200,
y: 100,
scaleX: 0.8,
scaleY: 0.8,
rotation: Math.PI / 4,
tint: 0xff0000,
alpha: 0.5,
});
你也可以使用简写:
🌐 You can also use the shorthand:
const particle = new Particle(Texture.from('spark.png'));
API 参考
🌐 API Reference