THREE.IcosahedronGeometry访问vertices数组返回undefined问题求助
问题成因
three.js 自r125版本起正式移除了传统Geometry类,所有内置几何体(包括IcosahedronGeometry、SphereGeometry)默认继承自BufferGeometry,不再暴露直接的vertices数组属性。你所观看的课程使用的是r125之前的旧版本three.js,因此演示代码可正常运行,你用新版本运行就会返回undefined。
正确获取顶点数组的方法
方法1:直接读取BufferGeometry的顶点属性(推荐)
当前版本的顶点坐标存储在geometry.attributes.position缓冲区属性中,可通过遍历该属性得到和旧版vertices结构一致的顶点数组:
const baseGeometry = new THREE.IcosahedronGeometry(1, 1); const positionAttr = baseGeometry.attributes.position; const points = []; for (let i = 0; i < positionAttr.count; i++) { points.push( new THREE.Vector3( positionAttr.getX(i), positionAttr.getY(i), positionAttr.getZ(i) ) ); } console.log(points);
方法2:兼容旧版API转换(仅适配存量旧代码)
如果需要沿用旧代码的vertices写法,可引入three.js官方提供的兼容模块将BufferGeometry转为旧版Geometry实例:
import { Geometry } from 'three/addons/extras/Geometry.js'; const baseGeometry = new THREE.IcosahedronGeometry(1, 1); const legacyGeometry = new Geometry().fromBufferGeometry(baseGeometry); const points = legacyGeometry.vertices; console.log(points);
内容的提问来源于stack exchange,提问作者Abdulsalam Almahdi
相关产品推荐
相关产品推荐

