How to target object within GLTF model with raycaster/animation

I’ve got a GLTF model made in Blender which contains a number of objects, I’m trying to create animations and popups that are triggered when you click on some of the objects. I’ve got as far as the raycaster recognising specific objects when clicked, for example when you click a tree, the console log shows the following:

object: Mesh {uuid: '34c42657-fd5d-4964-a72d-ebe7fddfca7d', name: 'Tree006', type: 'Mesh', parent: Group, children: Array(0), …}

Someone on this forum provided me with the gsap code needed to animate the camera to zoom into the object when clicked, but I can’t figure out how to actually target the object (eg ‘Tree006’) with the code. Here is what I have so far:

const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2()

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 ) {
        var object = intersects[0].object;
	    gsap.to( camera.position, {
    duration: 1, // seconds
    x: target.x,
    y: target.y,
    z: target.z,
    onUpdate: function() {
        camera.lookAt( center );
    }
} );
	}
}

Top of code add:
var mesh=[];
into model loader add:

gltf.scene.traverse(function(child) {
if(child.isMesh){ mesh[child.name]=child; }
}

Example:

loader.load( 'model.glb', function ( gltf ) {
scene.add( gltf.scene );
gltf.scene.traverse(function(child) {
if(child.isMesh){ mesh[child.name]=child; }
}
}

Then you can get models

gsap.to( camera.position, {
    duration: 1, // seconds
    x: mesh["Tree006"].position.x,
    y: mesh["Tree006"].position.y,
    z: mesh["Tree006"].position.z,
    onUpdate: function() {
        camera.lookAt( center );
    }
} );
1 Like

Thanks! So close, now I just need to target the object ‘Tree006’ ONLY when you click ‘Tree006’, currently it zooms into ‘Tree006’ when you click anywhere?

Yes anywhere. If need click tree006 then

if ( intersects.length > 0 && intersects[0].object.name="Tree006") {
        var object = intersects[0].object;
	    gsap.to( camera.position, {
    duration: 1, // seconds
    x: mesh["Tree006"].position.x,
    y: mesh["Tree006"].position.y,
    z: mesh["Tree006"].position.z,
    onUpdate: function() {
        camera.lookAt( center );
    }
1 Like

This code is not working unfortunately, there are errors.

post errors here so we can guide you…

VSCode doesnt seem to like some parts of the code, ill also post the errors in the console below

try to console the value of intersects so you understand better what is at 0th index

It just looks like a syntax error

it’s === not single equal too sign

1 Like

Yes that was the problem, thank you!

Never mind, try to debugging by consoling value, you understand better