Three.js v0.142.0: 从 Three.Geometry 到 Three.BufferGeometry 的粒子系统升级
在 Three.js v0.142.0 版本中,Three.Geometry 已经被废弃,建议使用 Three.BufferGeometry 来创建粒子系统。本文将演示如何将使用 Three.Geometry 的代码升级到 Three.BufferGeometry。
旧代码 (使用 Three.Geometry)
const particleCount = 1000;
const particles = new Three.Geometry();
for (let p = 0; p < particleCount; p++) {
const particle = new Three.Vector3(
Math.random() * 50 - 25,
Math.random() * 50 - 25,
Math.random() * 50 - 25
);
particles.vertices.push(particle);
}
新代码 (使用 Three.BufferGeometry)
const particleCount = 1000;
const particles = new Three.BufferGeometry();
const positions = new Float32Array(particleCount * 3);
for (let i = 0; i < particleCount; i++) {
const x = Math.random() * 50 - 25;
const y = Math.random() * 50 - 25;
const z = Math.random() * 50 - 25;
positions[i * 3] = x;
positions[i * 3 + 1] = y;
positions[i * 3 + 2] = z;
}
particles.setAttribute('position', new Three.BufferAttribute(positions, 3));
const particleMaterial = new Three.PointsMaterial({
size: 0.1,
color: 0xffffff
});
const particleSystem = new Three.Points(particles, particleMaterial);
scene.add(particleSystem);
升级步骤:
- **移除
Three.Geometry:**将代码中的Three.Geometry替换为Three.BufferGeometry。 - **创建
Float32Array:**使用Float32Array存储粒子位置数据,每个粒子需要 3 个浮点数 (x, y, z)。 - **设置
position属性:**使用setAttribute('position', ...)方法将Float32Array数据添加到BufferGeometry的position属性中。 - **创建
PointsMaterial:**使用PointsMaterial创建粒子材质。 - **创建
Points对象:**使用Points对象将粒子几何体和材质组合在一起。 - **将粒子系统添加到场景中:**使用
scene.add(...)将粒子系统添加到场景中。
通过这些简单的步骤,您可以将使用 Three.Geometry 的粒子系统代码升级到使用 Three.BufferGeometry,从而确保您的代码在最新版本的 Three.js 中正常运行。
原文地址: https://www.cveoy.top/t/topic/mLrF 著作权归作者所有。请勿转载和采集!