The AnimationMixer is refusing to start playing the animation from the gltf file

I have successfully imported a model using three.js and it works fine. Now, I am trying to run animations from a GLB file. Although I can retrieve the animation names with three.js, the TJS library fails to play my animations.

GLB FILE

There are two animations in the GLB file named "Intro" and "Rotate". By using this command console.log(gltf.animations);, I can see these animations. However, I encounter issues when trying to use them with the code snippet below:


        var scene, renderer;
        var camera;
        var mesh;
        // Other variables and functions...
        window.addEventListener('DOMContentLoaded', execFA());

Answer №1

Make sure to keep the animation mixer updated within the animation loop. Give this revised code a try

var scene, renderer;
var camera;
var mesh;
var clickDown;
var model;

var mixer, clock; // global variable declarations

var isMouseDown = false;

function executeFA() {


    scene = new THREE.Scene();

    clock = new THREE.Clock(); // instantiate clock


    camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
    camera.position.z = 25;
    camera.position.y = 15;


    renderer = new THREE.WebGLRenderer();
    renderer.setSize(window.innerWidth, window.innerHeight);
    document.getElementById('container').appendChild(renderer.domElement);

    renderer.setClearColor(0x00ffff, 1);
    renderer.gammaOutput = true;


    var light = new THREE.DirectionalLight("#c1582d", 1);
    var ambient = new THREE.AmbientLight("#85b2cd");
    light.position.set(0, -70, 100).normalize();
    scene.add(light);
    scene.add(ambient);

    var texture = new THREE.Texture();
    var manager = new THREE.LoadingManager();
    manager.onProgress = function(item, loaded, total) {};
    var onProgress = function(xhr) {};
    var onError = function(xhr) {};


    var loader = new THREE.GLTFLoader();

    // Load a glTF resource
    loader.load(
        './models/vc.glbf',
        function(gltf) {
            model = gltf;
            mesh = gltf.scene;
            mesh.scale.set(3, 3, 3);
            var animations = gltf.animations;

            console.log(gltf.animations);
            console.log(gltf.scenes);
            var clip = THREE.AnimationClip.findByName(animations, 'Intro');
            mixer = new THREE.AnimationMixer(mesh); 
            console.log(clip)

            animations.forEach(animation => {

                mixer.clipAction(animation).play();

            });

            animate();
            render();


            scene.add(mesh);

        },
        function(xhr) {

            console.log((xhr.loaded / xhr.total * 100) + '% loaded');

        },
        function(error) {

            console.log('An error happened', error);

        }
    );

    document.addEventListener("mousedown", onMouseDown);
    document.addEventListener("touchstart", onMouseDown);
    document.addEventListener("mouseup", onMouseUp);
    document.addEventListener("touchend", onMouseUp);
    document.addEventListener("mousemove", onMouseMove);
    document.addEventListener("touchmove", onMouseMove);

    render();
}

function animate() {
    requestAnimationFrame(animate);
}

function render() {
    if (model) {
        requestAnimationFrame(render);
        var delta = clock.getDelta();
        mixer.update(delta);
        renderer.render(scene, camera);
    }

}


function onMouseDown(event) {
    isMouseDown = true;
}


function onMouseMove(event) {
    if (isMouseDown) {
        if (mesh) {
            mesh.rotation.y = getMouseX(event) / 50;
            mesh.rotation.x = getMouseY(event) / 50;

        }
    }
}

function onMouseUp(event) {
    isMouseDown = false;
}

function getMouseX(event) {
    return event.type.indexOf("touch") == -1 ? event.clientX : event.touches[0].clientX;
}


function getMouseY(event) {
    return event.type.indexOf("touch") == -1 ? event.clientY : event.touches[0].clientY;
}

window.addEventListener('DOMContentLoaded', executeFA());

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error: The MUI Popper Component constantly closes when re-rendering due to props issue

I have been exploring how to structure a component incorporating MUI's Popover component, especially when dealing with dynamic props being passed to a controlled Slider component inside the Popover as well as the anchor element being updated dynamical ...

Adjust the height of an element when an animation is initiated (Angular)

Check out the transition I've set up to smoothly slide between my views: https://plnkr.co/edit/yhhdYuAl9Kpcqw5tDx55?p=preview To ensure that both 'panels' slide together, I need to position the view absolutely. However, this causes the view ...

The state variable is not accurately captured as it passes through various components

For the sake of readability, I have omitted certain sections of my original code. Apologies if this leads to any confusion! In App.js, there is a state variable defined as follows: const [tasks, setTasks] = useState([]) From App.js, the state varia ...

When you click on the text, the calendar will pop up for you to

When the text "SetExpiryDate" is clicked, a date picker opens. After selecting a date, the text changes to "Expires ${date}" where the selected date is inserted. If no date is selected, the text remains as it is. I'm curious how I can implement this ...

When validating with Sequelize, an error occurred due to one or more columns being undefined:

Hello everyone, I'm facing some issues. Can anyone explain why this.day_number and this.teacher_id are coming up as undefined? 'use strict' module.exports = (sequelize, DataTypes) => { const Teacher = sequelize.models.teachers ...

positioning a window.confirm dialog box in the center of the screen

I'm currently facing an issue with a dialog box that I have implemented successfully. However, I can't seem to get it centered on the page: <Button variant="danger" onClick={() => { if (window.confirm('Delete character?')) handle ...

Implementing event handlers with 'v-on' on dynamically inserted content using 'v-html' in Vue

Can Vue allow for the addition of v-on events on strings included in v-html? In this scenario, clicking the 'Maggie' link doesn't produce any action. It appears that it's not recognized by Vue. Is there an alternative method to achieve ...

When using window.open in Chrome on a dual screen setup, the browser will bring the new window back to the

When using the API window.open to open a new window with a specified left position in a dual screen setup (screen1 and screen2), Chrome behaves differently than IE and FF. In Chrome, if the invoking screen is on the right monitor, the left position always ...

Eliminating an element from an array without the need for iteration

I've been reviewing some documentation, but I have a hunch that there may be a simpler way to eliminate one element from an array without having to utilize an iteration loop. http://jsfiddle.net/G97bt/1/ Check out the updated jsFiddle example: http: ...

"Learn how to clear an input field using jQuery with this simple guide

I've gone through a few discussions, such as this one and that one, but I'm still struggling to clear the input field after submission. What is the simplest way to achieve this? This is my current approach: $(document).ready(function(){ $(& ...

Replicating a Bootstrap element without transferring all event listeners

Recently, I posted a query on Stack Overflow regarding the cloning of a bootstrap element while excluding the copied event listener. The solution provided was to refrain from passing true to the clone() function. Upon further reflection, I've realize ...

Properly aligning text with checkboxes using HTML/CSS and tags like <span> or <div>

My goal is to have the text displayed as a block in alignment with the checkbox, adjusting based on the sidebar's width. For reference: Current Layout Preferred Layout I have shared the code on CodePen (taking into account screen resolution and wi ...

WebSocket connection established on port 8888, while the web server is running on port 80 - incompatible to merge the two services

Here is some node.js server-side code that involves watching a file and sending modifications to the browser: var app = require('http').createServer(handler) , io = require('socket.io').listen(app) , fs = require('fs') a ...

What are the best techniques for distinguishing the selected selector in jQuery?

$('#select_id1, #select_id2, #select_id3').change(function() { // Depending on which select element has changed, 'str' should be set accordingly. // For '#select_id1', 'str' should be equal to 'select_id ...

Using Regex in JavaScript to split a string based on a saved pattern

I have a specific sentence to work with: var sentence="example of+a+string"; My goal is to split the string by the + symbol only when it occurs after the word "of". When attempting this with the code: sentence.split(/of(\+)/) The result splits th ...

Retrieve the current URL of an IFRAME

How can I easily retrieve the current URL from an embedded iframe? The user will be navigating through various web pages. I assume that some JavaScript code would be needed for this task. ...

The file module.js is encountering an error at line 327 because it is unable to locate the module named 'express

Hey there, I'm new to nodejs and whenever I run a file in the command prompt like:- C:\demoData>node demo.js I encounter an error like this: module.js:327 throw err; ^ Error: Cannot find module 'express' at Function.M ...

How can I dynamically remove an option from a select dropdown if it already exists in another option using jQuery?

In order to achieve the desired functionality, I need to dynamically adjust the select options based on user input. Additionally, I want the selection to update automatically upon a change event. var dynamicCount = 1; $('#add').click(function ...

What is the best way to experiment with angular-ui-tinymce within a tabset using Plunker?

I am currently experimenting with angular-ui-tinymce by incorporating it into a Plunkr. Can anyone assist me in integrating the necessary files for angular-ui-tinymce into the Plunkr so that I can showcase its functionality? Currently, I have this Plunker ...

Grouping JavaScript nested properties by keys

I have a specific object structure in my code that I need to work with: { "changeRequest": [{ "acrId": 11, "ccrId": "", "message": "test message" }, ...