Play Animation on click GLTF

Hi I am trying to play an animation on click so far the Idle animation is playing fine but I can’t seen to get the walking animation to play on a click, what Am I doing wrong?

Snippet:

 //Load
                   var action, model2, mixer2, clock, gltf2;
                    loader.load('scene.gltf', function(gltf2) {
	             model2 = gltf2.scene;
	            gltf2.scene.traverse(function(child) {
	                if (child.isMesh) {
	                    roughnessMipmapper.generateMipmaps(child.material);
	                }
	            });
	           
	            scene.add(model2);
	            roughnessMipmapper.dispose();
	            
               //Play Idle
                mixer2 = new THREE.AnimationMixer( model2 );
		action = mixer2.clipAction( gltf2.animations[ 0 ] );
		action.play();
	            
	          
	        });
	         //Load end
             
               //Click 
               function onClick() {
                
                    if (intersects[0].object.name == 'CharacterOne') {
              $('body').css('cursor', 'default');
             
	    mixer2 = new THREE.AnimationMixer( model2 );
		action = mixer2.clipAction( gltf2.animations[ 1 ] );
		action.play();

           }
      }

Uncaught TypeError: Cannot read property ‘animations’ of undefined
at HTMLCanvasElement.onClick

It seems your onClick event listener has no acess to the gltf2 variable. Try to declare it in global scope so it’s reachable for all lines of code that refer to it.

2 Likes

How Would I define function(gltf2) as a var ?
gltf2 = gltf2.scene; ?
I did try:
model2.animations[ 1 ] but that didn’t work and model2 is global

Do it like so:

loader.load('scene.gltf', function(gltf) {

    gltf2 = gltf;

1 Like

I’ve changed a bit to

    var gltfPlayer, model, model2, mixer, mixer2, action;
    //Loader 2
     model2 = gltf2.scene;
     gltfPlayer = gltf2;
    mixer2 = new THREE.AnimationMixer( model2 );
    		action = mixer2.clipAction( gltf2.animations[ 0 ] );

It works perfectly now on click but it seems to of stopped my windmill from playing

     mixer = new THREE.AnimationMixer(model);
    	            gltf.animations.forEach((clip) => {
    	                mixer.clipAction(clip).play();
    	            });

Any idea’s?

I Needed another clock my mistake! thanks