three.js的InstancedMesh使用

131 阅读1分钟

three.js的InstancedMesh使用

官方文档:

官方文档
官方示例

实例化网格( InstancedMesh )

这个类合 Mesh 类似。 你可以使用 InstancedMesh 来渲染大量具有相同几何体与材质、但具有不同世界变换的物体。 使用 InstancedMesh 将帮助你减少 draw call 的数量,从而提升你应用程序的整体渲染性能。

使用代码

先看一下 Mesh 的使用

const geometry = new THREE.BoxGeometry( 1, 1, 1 );
const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
const mesh = new THREE.Mesh( geometry, material );
scene.add( mesh );

InstancedMesh 的使用

const count = 1000; // 要创建 1000 的mesh
const geometry = new THREE.BoxGeometry( 1, 1, 1 );
const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
const mesh = new THREE.InstancedMesh( geometry, material, count );

// 修改每个mesh的位置、颜色等属性
const matrix = new THREE.Matrix4();
for(let i = 0; i < count; i++) {
    matrix.setPosition( x, y, z ); // 位置
    mesh.setMatrixAt( i, matrix ); // 修改位置

    mesh.setColorAt( i, color ); // 修改颜色
}

对于一些需要贴图的 mesh 就直接修改material就行。如果需要旋转、修改位置等,就和普通的mesh一样操作即可。