Created
November 19, 2017 14:12
-
-
Save kevincharm/bf12a2c673b43a3988f0f171a05794c1 to your computer and use it in GitHub Desktop.
Clone an already-loaded FBX model in three.js and be able to animate it. Adapted from: https://gist.github.com/cdata/f2d7a6ccdec071839bc1954c32595e87
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const cloneFbx = (fbx) => { | |
const clone = fbx.clone(true) | |
clone.animations = fbx.animations | |
clone.skeleton = { bones: [] } | |
const skinnedMeshes = {} | |
fbx.traverse(node => { | |
if (node.isSkinnedMesh) { | |
skinnedMeshes[node.name] = node | |
} | |
}) | |
const cloneBones = {} | |
const cloneSkinnedMeshes = {} | |
clone.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 THREE.Skeleton(orderedCloneBones, skeleton.boneInverses), | |
cloneSkinnedMesh.matrixWorld) | |
// For animation to work correctly: | |
clone.skeleton.bones.push(cloneSkinnedMesh) | |
clone.skeleton.bones.push(...orderedCloneBones) | |
} | |
return clone | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment