问题
I am looking for some kind of event handling for geometries/cameras/lights(things we add to scene) in three.js ?
I googled but couldn't find anything relevant. I did a simple Sphere rendering and tried to see the DIV contents in firebug, but there's just one canvas, and adding any "onclick" to the canvas makes the event for all the canvas, that is, its not just for the sphere or light.
Any suggestions ?
回答1:
You need to a couple o things to get interactivity in 3D:
- get a vector for the mouse position
- unproject the mouse vector based on the camera
- shot a ray from the camera position, towards the unprojected mouse vector
- check what object(s) interesect with that ray and update accordingly.
It might sound complicated, but the code's already there:
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 );
}
*/
}
This code above from the canvas_interactive_cubes example that comes with the library. When in doubt, it's always good to check if there's an example that solves the problem already.

来源:https://stackoverflow.com/questions/9145383/event-handling-for-geometries-in-three-js