To achieve interactivity in a 3D environment, you will need to follow these steps:
- Obtain a vector for the mouse position
- Unproject the mouse vector based on the camera settings
- Create a ray originating from the camera position towards the unprojected mouse vector
- Determine which object(s) intersect with the ray and update them accordingly
Although it may seem complex, the necessary code has already been provided:
function onDocumentMouseDown( event ) {
event.preventDefault();
var vector = new THREE.Vector3( ( event.clientX / window.innerWidth ) * 2 - 1, - ( event.clientY / window.innerHeight ) * 2 + 1, 0.5 );
projector.unprojectVector( vector, camera );
var ray = new THREE.Ray( camera.position, vector.subSelf( camera.position ).normalize() );
var intersects = ray.intersectObjects( objects );
if ( intersects.length > 0 ) {
intersects[ 0 ].object.material.color.setHex( Math.random() * 0xffffff );
var particle = new THREE.Particle( particleMaterial );
particle.position = intersects[ 0 ].point;
particle.scale.x = particle.scale.y = 8;
scene.add( particle );
}
/*
// Parse all the faces
for ( var i in intersects ) {
intersects[ i ].face.material[ 0 ].color.setHex( Math.random() * 0xffffff | 0x80000000 );
}
*/
}
The code snippet above is extracted from the canvas_interactive_cubes example provided within the library.
When facing difficulties, always refer to existing examples that might offer a solution.