在 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);

升级步骤:

  1. **移除 Three.Geometry:**将代码中的 Three.Geometry 替换为 Three.BufferGeometry。
  2. **创建 Float32Array:**使用 Float32Array 存储粒子位置数据,每个粒子需要 3 个浮点数 (x, y, z)。
  3. **设置 position 属性:**使用 setAttribute('position', ...) 方法将 Float32Array 数据添加到 BufferGeometry 的 position 属性中。
  4. **创建 PointsMaterial:**使用 PointsMaterial 创建粒子材质。
  5. **创建 Points 对象:**使用 Points 对象将粒子几何体和材质组合在一起。
  6. **将粒子系统添加到场景中:**使用 scene.add(...) 将粒子系统添加到场景中。

通过这些简单的步骤,您可以将使用 Three.Geometry 的粒子系统代码升级到使用 Three.BufferGeometry,从而确保您的代码在最新版本的 Three.js 中正常运行。

Three.js v0.142.0: 从 Three.Geometry 到 Three.BufferGeometry 的粒子系统升级

原文地址: https://www.cveoy.top/t/topic/mLrF 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录