设置Buffer Geometry的position属性时出现NaN错误求助
解决THREE.BufferGeometry.computeBoundingSphere() NaN报错问题
这个报错的核心是你的position属性数组里混入了NaN值,通常是Math.sin()/Math.cos()传入无效参数导致的,按以下步骤排查修复:
- 检查角度计算逻辑:确保传入sin/cos的参数是合法弧度值,比如循环中的角度变量是否未初始化、是否被赋值为undefined/NaN
- 确认循环赋值完整性:遍历生成position数组时,每个xyz分量都要正确赋值,不能出现数组空位
- 验证变量有效性:所有参与计算的变量(比如半径、分段数、步长)都要提前定义为有效数字,不能留空或设为非数值类型
给你一段修正后的示例代码,参考这个逻辑调整你的实现:
const geometry = new THREE.BufferGeometry(); const positions = []; const totalSegments = 32; // 自定义分段数 const circleRadius = 5; // 自定义半径 const angleStep = Math.PI * 2 / totalSegments; // 计算每段的弧度步长 // 循环生成顶点坐标 for (let i = 0; i <= totalSegments; i++) { const currentAngle = i * angleStep; const x = Math.cos(currentAngle) * circleRadius; const y = Math.sin(currentAngle) * circleRadius; const z = 0; positions.push(x, y, z); } // 设置position属性 geometry.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3)); geometry.computeBoundingSphere(); // 此时不会再触发NaN报错
内容的提问来源于stack exchange,提问作者Aman
相关产品推荐
相关产品推荐

