ThreeJS Example webgl_instancing_raycast

217 阅读1分钟

threejs.org/examples/#w…

image.png

  • 基本数量和射线
const amount = parseInt( window.location.search.substr( 1 ) ) || 10; 
const count = Math.pow( amount, 3 ); //几何体的个数

const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2( 1, 1 );
  • instanceMesh
const geometry = new THREE.IcosahedronGeometry( 0.5, 3 );
const material = new THREE.MeshPhongMaterial();

mesh = new THREE.InstancedMesh( geometry, material, count );
  • 编排
let i = 0;
const offset = ( amount - 1 ) / 2;
const matrix = new THREE.Matrix4();
for ( let x = 0; x < amount; x ++ ) {
        for ( let y = 0; y < amount; y ++ ) { 
                for ( let z = 0; z < amount; z ++ ) {
                        matrix.setPosition( offset - x, offset - y, offset - z );
                        mesh.setMatrixAt( i, matrix ); //setMatrixAt方法
                        mesh.setColorAt( i, color );
                        i ++;
                }
        }
}
  • 捕获
raycaster.setFromCamera( mouse, camera );
const intersection = raycaster.intersectObject( mesh );
if ( intersection.length > 0 ) {
        const instanceId = intersection[ 0 ].instanceId; //通过获取到ID来进行下一步操作 ID不是Mesh
        mesh.setColorAt( instanceId, color.setHex( Math.random() * 0xffffff ) );
        mesh.instanceColor.needsUpdate = true;
}