简体   繁体   中英

THREE.js loading the same animated GLB in a loop only plays the last loaded model

I am trying to load a swarm of animated butterflies in a loop, for some reason only one of them, either the first or the last actually plays, I presume it's because I need to clone the gltf.scene but there is a known bug with cloning animated gltfs.

Any help appreciated.

let mixer = [];
    const butt_loader = new THREE.GLTFLoader();
    for(var i=0;i<40;i++){
    butt_loader.load('butterfly_rigged.glb', function (gltf) {
    var butt_scale = 1;

        var model = gltf.scene;
        model.position.z = -3 - Math.random()*7;
        model.position.x = 6*Math.random();
        model.position.y = 6*Math.random();
        model.scale.x = butt_scale*Math.random();
        model.scale.y = butt_scale*Math.random();
        model.scale.z = butt_scale*Math.random();

        model.rotation.y = -Math.PI/4;
        model.rotation.z = 0.1;
        model.rotation.x = Math.PI/4;
        butt_scene.add(model.clone());

        mixer.push(new THREE.AnimationMixer(model));
        gltf.animations.forEach((clip) => {
        mixer[mixer.length-1].clipAction(clip).play();
        }); 
    });
    }
    var butt_clock = new THREE.Clock();
    function render_butt(){
    for(var i=0;i<mixer.length;i++){
        if(mixer[i]!=null) mixer[i].update(butt_clock.getDelta());
    }
    requestAnimationFrame( render_butt );   
    butt_ren.clear();
    butt_ren.render( butt_scene, butt_camera );
    }
    render_butt();

This part:

    for(var i=0;i<mixer.length;i++){
        if(mixer[i]!=null) mixer[i].update(butt_clock.getDelta());
    }

better to replace with this:

    var delta = butt_clock.getDelta();
    for(var i=0;i<mixer.length;i++){
        if(mixer[i]!=null) mixer[i].update(delta);
    }

.getDelta() gets delta since last call of it, so when you call it in the loop, all delta will be 0 , except for the first iteration. When you put it off of the loop, then you'll get it once and pass the same (non-zero) value to all mixers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM