Clicking on gltf models

I was wandering if there is any method in three.js that allows the user to click on a model (for example an imported gltf file from blender) and as a result of the click something else to happen (for example a pop up box or an image is displayed).

I was trying to look it up in the three.js website but all found was the raycaster class. But from my understanding this will only work with objects that have a mesh and thus only the ones that are made in three.js itself with the geometry properties.

I also found tutorials with the use of threex.domevents. But once again I don’t see how this can be used with the models imported from blender. I tried using it but it only caused my models to disappear from the screen.

So is there another solution? or is it impossible?

I really appreciate the help,thank you very much.

I recommend you use raycaster.

Raycaster will not only work on objects made in THREE.js itself. It will also work on GLTF, GLB, OBJ, FBX, … models.

1 Like

/cc

Here is the official glTF example enhanced with basic raycasting:

https://jsfiddle.net/3t2g4xjr/

Instead of logging something to the console, you can of course perform an arbitrary action. Most important part is the onClick() handler which triggers the actual intersection:

function onClick( event ) {

	event.preventDefault();

	mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
	mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;

	raycaster.setFromCamera( mouse, camera );

	var intersects = raycaster.intersectObjects( scene.children, true );

	if ( intersects.length > 0 ) {

		console.log( 'Intersection:', intersects[ 0 ] );

	}

}
1 Like