A copy of an animated object loses its animations

Hello,

When I copy any animated object (GLTF based), it loses its animations. Here’s a code I use:

//Let's assume that 'gltf' is a target object with scene, assets, animations, etc.
var mixers = [];
var clocks = [];
let gltfClone = threeCloneGltf(gltf);

var clocks.push(new THREE.Clock());  
var mixer = new THREE.AnimationMixer( gltfClone.scene.children[0] );


let clip = gltfClone.animations[ 0 ];
let action = mixer.clipAction( clip ); 
action.play();
mixers.push(mixer);
 
function threeCloneGltf(gltf){

    const clone = {
        animations: gltf.animations,
        scene: gltf.scene.clone(true)
    };

    const skinnedMeshes = {};

    gltf.scene.traverse(node => {
        if (node.isSkinnedMesh) {
            skinnedMeshes[node.name] = node;
        }
    });

    const cloneBones = {};
    const cloneSkinnedMeshes = {};

    clone.scene.traverse(node => {
        if (node.isBone) {
            cloneBones[node.name] = node;
        }

        if (node.isSkinnedMesh) {
            cloneSkinnedMeshes[node.name] = node;
        }
    });

    for (let name in skinnedMeshes) {
        const skinnedMesh = skinnedMeshes[name];
        const skeleton = skinnedMesh.skeleton;
        const cloneSkinnedMesh = cloneSkinnedMeshes[name];

        const orderedCloneBones = [];

        for (let i = 0; i < skeleton.bones.length; ++i) {
            const cloneBone = cloneBones[skeleton.bones[i].name];
            orderedCloneBones.push(cloneBone);
        }

        cloneSkinnedMesh.bind(
            new Skeleton(orderedCloneBones, skeleton.boneInverses),
            cloneSkinnedMesh.matrixWorld);
    }

    return clone;

}

function render(){    

    for(let key in mixers){
        
        let animation = mixers[key];
        let dt = clocks[key].getDelta();
        
        animation.update( dt );
    }

    renderer.render(scene, camera);
  
    
}  

Technically an object seems to copied correctly: it has new id and all mixes are copied, but the object is still.

1 Like

See https://github.com/mrdoob/three.js/pull/14494 for a suggested way to clone a SkinnedMesh, while keeping bone relationships intact.

1 Like