Robot arm - inverse kinematics

That is a little tough to do in BJS itself, but having separate meshes would make it at least possible.

First, you have to add bone indexes & weights to every vertex of each mesh. If you have 1 mesh per bone, then set the index to the index of the bone to match.

var doMesh = function(mesh, index) {
    const n = mesh.getTotalVertices();
    const indexes = new Float32Array(n * 4);
    const weights = new Float32Array(n * 4);
    for (let i = 0; i < n; i++) {
        indexes[i * 4] = index;
        weights[i * 4] = 1;
    }
    mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, indexes),
    mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, weights),
}

The skeleton is going to be a lot trickier. Not a lot of code, but you are going to need “magic” numbers.

const skeleton = new BABYLON.Skeleton("name", "0", scene);
let rootBone = new BABYLON.Bone("K2-Root", skeleton, null, BABYLON.Matrix.FromValues(1,0,.0001,0,0,1,0,0,.0001,0,-1,0,0,0,0,1));
let bone1 = new BABYLON.Bone("K2-SpineLower", skeleton, rootBone, BABYLON.Matrix.FromValues(1,0,.0001,0,0,1,0,0,-.0001,0,1,0,0,.8457,0,1));
let bone2 = new BABYLON.Bone("K2-SpineUpper", skeleton, bone1, BABYLON.Matrix.FromValues(1,0,0,0,0,.9895,-.1448,0,0,.1448,.9895,0,0,.2254,0,1));

This is an abbreviated list of a computer generated section from my Blender source code generator. You would not build your matrices with hardcoded values, but probably starting with a static Matrix method to instance one for either the translation or rotation, then another operation to insert the other. Also child bones need to also be multiplied by the inverted parent matrix.

Maybe someone could help you with this, but not me.

1 Like