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)
报错根因与修复方法
- 存在两处关键实现错误:
- 初始化的BufferGeometry实例
geoR没有被实际使用,生成的顶点数据全部存在普通JS数组this.rainGeo中,没有写入BufferGeometry的属性集 - 向
THREE.Points构造函数传参时,将普通JS数组直接作为几何体传入,而非有效的BufferGeometry实例
- 初始化的BufferGeometry实例
- 修复步骤:
- 将遍历生成的所有顶点坐标整理为连续的数值序列,存入Float32Array类型的顶点缓冲区
- 将顶点缓冲区绑定为BufferGeometry的position属性,完成几何体实例的构建
- 将合法的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
相关产品推荐
相关产品推荐

