Nicolas S.Xu
Nicolas S.Xu

Reputation: 14504

How to use InstancedBufferGeometry to do raycasting in ThreeJS?

There is an example to show how to raycast using BufferGeometry, but how to do raycast using InstancedBufferGeometry?

For example, add raycasting capability to this demo? https://threejs.org/examples/?q=instancing#webgl_buffergeometry_instancing

Upvotes: 1

Views: 545

Answers (1)

Mugen87
Mugen87

Reputation: 31016

Raycasting support for meshes with InstancedBufferGeometry was never implemented. However, you can use the new InstancedMesh class which was added with R109 and which does support raycasting. Check out the following example to see this feature in action:

https://threejs.org/examples/webgl_instancing_raycast

The important raycasting code section looks like so:

var intersection = raycaster.intersectObject( mesh ); // mesh is type of InstancedMesh

if ( intersection.length > 0 ) {

    var instanceId = intersection[ 0 ].instanceId;

    mesh.getMatrixAt( instanceId, instanceMatrix ); // get local transformation matrix of the instance
    matrix.multiplyMatrices( instanceMatrix, rotationMatrix ); // modify it
    mesh.setMatrixAt( instanceId, matrix ); // write it back

    mesh.instanceMatrix.needsUpdate = true;

}

three.js R113

Upvotes: 3

Related Questions