react-three/fiber使用InstancedMesh创建实例化三角形未生效问题咨询
问题原因
- InstancedMesh 不会为实例自动生成默认变换矩阵,即使仅创建1个实例,也需要手动为每个实例设置矩阵,未设置矩阵时实例默认不会渲染
- 需确认代码中
position变量的值与之前正常渲染的array值完全一致,若顶点数据错误也会导致渲染异常 - 部分低版本react-three-fiber对InstancedMesh传入
null作为初始化geometry、material的兼容存在问题,也可能导致渲染失败
解决方案
- 首先确保顶点数据正确,
position变量取值如下:
const position = new Float32Array([0, 20, 0, 0, 0, 0, 20, 0, 0]);
- 组件挂载后通过ref为InstancedMesh设置实例矩阵,标记矩阵更新:
import { useRef, useEffect } from 'react' import * as THREE from 'three' // 组件内代码 const meshRef = useRef<THREE.InstancedMesh>(null) useEffect(() => { if (!meshRef.current) return // 单位矩阵,保持实例原始位置、旋转、缩放 const instanceMatrix = new THREE.Matrix4() meshRef.current.setMatrixAt(0, instanceMatrix) // 必须标记矩阵属性需要更新,否则修改不会生效 meshRef.current.instanceMatrix.needsUpdate = true }, [])
- 若仍渲染失败,可将初始化参数替换为提前声明的空geometry和material:
<instancedMesh ref={meshRef} args={[new THREE.BufferGeometry(), new THREE.MeshBasicMaterial(), 1]}> {/* 原有geometry、material子元素不变 */} </instancedMesh>
内容的提问来源于stack exchange,提问作者beewest
相关产品推荐
相关产品推荐

