catch the click event on a specific mesh in the renderer
You can generate a callback like this. First define your callback function for each object:
mesh.callback = function() { console.log( this.name ); }
Then follow the standard picking pattern:
var raycaster = new THREE.Raycaster();
var mouse = new THREE.Vector2();
function onDocumentMouseDown( event ) {
event.preventDefault();
mouse.x = ( event.clientX / renderer.domElement.clientWidth ) * 2 - 1;
mouse.y = - ( event.clientY / renderer.domElement.clientHeight ) * 2 + 1;
raycaster.setFromCamera( mouse, camera );
var intersects = raycaster.intersectObjects( objects );
if ( intersects.length > 0 ) {
intersects[0].object.callback();
}
}
EDIT: updated to three.js r.70
Create a click handler
window.addEventListener('click', onDocumentMouseDown, false);
Define the function onDocumentMouseDown, note that raycaster the difference in above answer is the index position of the object clicked!
var raycaster = new THREE.Raycaster(); var mouse = new THREE.Vector2(); function onDocumentMouseDown( event ) { event.preventDefault(); mouse.x = ( event.clientX / renderer.domElement.clientWidth ) * 2 - 1; mouse.y = - ( event.clientY / renderer.domElement.clientHeight ) * 2 + 1; raycaster.setFromCamera( mouse, camera ); console.log(scene.children); var intersects = raycaster.intersectObjects( scene.children ); console.log(intersects[1]); if ( intersects.length > 0 ) { intersects[1].object.callback(); }}
Define the Mesh object
var mesh_menu_title = new THREE.Mesh(geometry_menu, materials_menu); mesh_menu_title.name = 'select_lang'; mesh_menu_title.callback = function() { select_language();} scene.add(mesh_menu_title);
define the callback function
function select_language(){ var selectedObject = scene.getObjectByName("select_lang"); scene.remove( selectedObject ); var selectedObject = scene.getObjectByName("start"); scene.remove( selectedObject ); var selectedObject = scene.getObjectByName("menu"); scene.remove( selectedObject ); }
So this code above will handle specific object clicked inside my canvas, then callback a function, the "mesh.callback" and it will remove some scene childs from the canvas.
It doesn't work if you use intersects[0].object.callback(); because at the index 0 the stored object are the vertices.