You need to enable JavaScript to run this app. three.js替换Geometry为BufferGeometry做雨效果时报center属性读取错误
优惠活动
大模型
产品
解决方案
定价
更多

three.js替换Geometry为BufferGeometry做雨效果时报center属性读取错误

Three.js 实现雨粒子报错解决

问题场景

  • 已学习编程数月,正在深入学习three.js与React技术,跟随教程开发真实感雨背景效果,此前开发流程进展顺利,进入雨粒子功能开发环节后出现连续报错
  • 初次运行教程内置的雨粒子实现代码时,触发three.js 未导出 Geometry 类的错误,查阅资料确认新版本three.js已将废弃的Geometry类替换为BufferGeometry作为标准几何体实现
  • 尝试替换类名修复后,旧报错消除,但在node_modules/three/build/three.module.js:4534位置触发新报错:Cannot read property 'center' of undefined,无法定位具体问题原因

原教程实现代码

rainGeo = new THREE.Geometry();
for(let i=0;i<rainCount;i++) {
  rainDrop = new THREE.Vector3(
    Math.random() * 400 -200,
    Math.random() * 500 - 250,
    Math.random() * 400 - 200
  );
  rainDrop.velocity = {};
  rainDrop.velocity = 0;
  rainGeo.vertices.push(rainDrop);
}
rainMaterial = new THREE.PointsMaterial({
  color: 0xaaaaaa,
  size: 0.1,
  transparent: true
});
rain = new THREE.Points(rainGeo,rainMaterial);
scene.add(rain);

当前自行修改的代码

this.rainCount = 15000
this.rainGeo = []
this.geoR = new THREE.BufferGeometry();
for( let i=0; i< this.rainCount; i++) {
  this.rainGeo.push(
    new THREE.Vector3(
      Math.random() * 400 - 200,
      Math.random() * 400 - 250,
      Math.random() * 400 - 200
    )
    ) 
};

this.rainMaterial = new THREE.PointsMaterial({
  color: 0xaaaaaa,
  size: 0.1,
  transparent: true
})
this.rain = new THREE.Points(this.rainGeo, this.rainMaterial);
this.scene.add(this.rain)

报错根因与修复方法

  • 存在两处关键实现错误:
    1. 初始化的BufferGeometry实例geoR没有被实际使用,生成的顶点数据全部存在普通JS数组this.rainGeo中,没有写入BufferGeometry的属性集
    2. 向THREE.Points构造函数传参时,将普通JS数组直接作为几何体传入,而非有效的BufferGeometry实例
  • 修复步骤:
    1. 将遍历生成的所有顶点坐标整理为连续的数值序列,存入Float32Array类型的顶点缓冲区
    2. 将顶点缓冲区绑定为BufferGeometry的position属性,完成几何体实例的构建
    3. 将合法的BufferGeometry实例作为第一参数传入THREE.Points构造函数
  • 修复后的可用代码示例:
this.rainCount = 15000
// 初始化BufferGeometry实例
this.rainGeo = new THREE.BufferGeometry();
const rainPositions = [];
for( let i=0; i< this.rainCount; i++) {
  // 生成雨粒子的三维坐标
  const x = Math.random() * 400 - 200;
  const y = Math.random() * 500 - 250;
  const z = Math.random() * 400 - 200;
  // 将坐标按x/y/z顺序存入连续数组
  rainPositions.push(x, y, z);
};
// 将顶点数据写入BufferGeometry的position属性
this.rainGeo.setAttribute('position', new THREE.Float32BufferAttribute(rainPositions, 3));

this.rainMaterial = new THREE.PointsMaterial({
  color: 0xaaaaaa,
  size: 0.1,
  transparent: true
})
// 传入合法的BufferGeometry实例构建Points对象
this.rain = new THREE.Points(this.rainGeo, this.rainMaterial);
this.scene.add(this.rain)
  • 注意:如果需要给雨粒子添加下落速度的自定义属性,可通过扩展自定义BufferAttribute实现,不再依赖旧版Geometry挂载动态属性的能力。

内容的提问来源于stack exchange,提问作者Brandonops

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.25 04:24:01