Reputation: 381
I am new to three.js, I am try to create a click event for a mesh I have created :
const geometry = new THREE.BoxBufferGeometry(size,size*0.5,size);
const material = new THREE.MeshStandardMaterial({color:0x00aa00 });
var option1 = new THREE.Mesh(geometry, material);
option1.position.set( 6, 5, 1)
// option1.callback = objectClickHandler;
// option1.on('click', function(ev) {
// console.log(ev)
// });
console.log(option1)
scene.add(option1)
But this is not working. onclick I will hide and show the object I have imported. But not able to do so as click event is not triggering.Help would be much appreciated.
Upvotes: 3
Views: 3268
Reputation: 747
everything happens in three.js is only in this one DOM that is the canvas.
to detect a click on a mesh, what you do is:
and to check if mouse is on mesh, you use RayCaster.
it should be something like this:
var raycaster = new THREE.Raycaster();
var mouse = new THREE.Vector2();
var targetMesh
function onMouseClick( event ) {
raycaster.setFromCamera( mouse, camera );
var isIntersected = raycaster.intersectObject( targetMesh );
if (isIntersected) {
console.log('Mesh clicked!')
}
}
function onMouseMove( event ) {
mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
}
window.addEventListener( 'mouseclick', onMouseClick, false );
window.addEventListener( 'mousemove', onMouseMove, false );
documents: https://threejs.org/docs/#api/en/core/Raycaster
Upvotes: 9