Atul Verma
Atul Verma

Reputation: 381

How to add event for a mesh in threejs?

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

Answers (1)

Jay Li
Jay Li

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:

  1. add a click event listener on the canvas.
  2. check if mouse is on the mesh when clicked.

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

Related Questions