Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Three.js attaching object to bone

Is there any way to attach mesh to bone? For example I load animated .js character and i want to attach weapon to it's hand.

like image 234
Gugis Avatar asked Sep 26 '13 14:09

Gugis


2 Answers

It is possible using a few simple hacks on the Bone and Object3D prototype. Since bones inherit from Object3D, they may have children, so we can easily .add() a mesh to any bone.

However, the SkinnedMesh will only call updateMatrixWorld() on non-Bone children, and update() for Bone children. Additionally, bones call update() for each of its children (regardless of wether it is a bone or not). The following snippets change that behavior:

// modify bone update function to also update its world matrix
// possibly do this only to skeletons you need it for, not for all bones
var update = THREE.Bone.prototype.update;
THREE.Bone.prototype.update = function(parentSkinMatrix, forceUpdate) {
    update.call(this, parentSkinMatrix, forceUpdate);
    this.updateMatrixWorld( true );
};

// add noop update function to Object3D prototype
// so any Object3D may be a child of a Bone
THREE.Object3D.prototype.update = function() {};

// create buffalo ...

// create a mesh and add it to some bone
var mesh = new THREE.Mesh( new THREE.SphereGeometry(20), new THREE.MeshNormalMaterial() );

var bone = buffalo.bones[5];
bone.add(mesh);
like image 68
morris4 Avatar answered Oct 19 '22 06:10

morris4


Three.js Version 68 handles this out of the box, but a bit different. No changing of internal functions is required.

It now works like this:

the bone hierarchy is now found in the children of the SkinnedMesh.

Find the bone in the children list and simply attach the object to it:

player.children[0].add(testObj);

Note: If you have a bone hierarchy (for example in your exported blender model) then this is represented in three.js too. If you target bone has a parent bone it will look like this:

player.children[0].children[1].add(testObj);
like image 33
JPS Avatar answered Oct 19 '22 05:10

JPS