Three.js使用PlaneGeometry调用vertices报TypeScript属性不存在问题求助
报错原因
Three.js 从r125版本开始正式废弃了旧的Geometry类,所有内置几何体默认使用BufferGeometry实现,官方的TypeScript类型定义里PlaneGeometry已归属BufferGeometry类型。BufferGeometry本身不存在vertices属性,所以类型检查会报错。运行正常是因为你实际加载的three.js版本保留了旧Geometry的兼容实现,或者代码里引入了兼容补丁。
解决方案
方案1:改用BufferGeometry标准API(推荐)
抛弃旧的vertices属性写法,通过position缓冲区属性操作顶点,符合新版three.js设计规范,性能更高且无类型问题:
// 获取position顶点属性 const positionAttr = this.particles.geometry.getAttribute('position'); // 遍历操作顶点,示例为修改第i个顶点的坐标 for (let i = 0; i < positionAttr.count; i++) { const x = positionAttr.getX(i); const y = positionAttr.getY(i); const z = positionAttr.getZ(i); // 你的自定义逻辑 positionAttr.setXYZ(i, x, y, z + Math.random()); } // 修改后标记属性需要更新 positionAttr.needsUpdate = true;
方案2:类型断言兼容旧写法(临时过渡用)
如果不想修改原有逻辑,直接给geometry做类型断言跳过类型检查即可:
// 强制断言为旧Geometry类型 const geometry = this.particles.geometry as unknown as THREE.Geometry; const vertices = geometry.vertices; // 后续沿用原有操作逻辑即可
注意该方案仅适合临时过渡,后续three.js彻底移除Geometry兼容后运行会报错。
方案3:显式创建旧Geometry实例
如果你的three.js版本还保留旧Geometry的导出,可以直接创建Geometry实例代替内置的PlaneGeometry:
const geometry = new THREE.Geometry(); // 手动填充顶点数据 geometry.vertices.push( new THREE.Vector3(-1, -1, 0), new THREE.Vector3(1, -1, 0), new THREE.Vector3(1, 1, 0), new THREE.Vector3(-1, 1, 0) ); // 设置面 geometry.faces.push(new THREE.Face3(0, 1, 2), new THREE.Face3(0, 2, 3));
内容的提问来源于stack exchange,提问作者Arjun M Nair
相关产品推荐
相关产品推荐

