BabylonJS - Bones and Skeletons



Babylonjs offers APIs to create skeletons and bones.

Syntax

Let us now see the syntax for different functions.

For Skeleton

BABYLON.Skeleton = function (name, id, scene)

For Bone

BABYLON.Bone = function (name, skeleton, parentBone, matrix)

Skeletons and Bones can be created using blender and the same can be exported in .babylonjs.

Demo

<!doctype html>
<html>
   <head>
      <meta charset = "utf-8">
      <title>BabylonJs - Basic Element-Creating Scene</title>
      <script src = "babylon.js"></script>
      <style>
         canvas {width: 100%; height: 100%;}
      </style>
   </head>

   <body>
      <canvas id = "renderCanvas"></canvas>
      <script type = "text/javascript">
         var canvas = document.getElementById("renderCanvas");
         var engine = new BABYLON.Engine(canvas, true);
         var createScene  = function() {
            var scene = new BABYLON.Scene(engine);

            //Adding a light
            var light = new BABYLON.PointLight("Omni", new BABYLON.Vector3(20, 20, 100), scene);

            //Adding an Arc Rotate Camera
            var camera = new BABYLON.ArcRotateCamera("Camera", 0, 0.8, 100, BABYLON.Vector3.Zero(), scene);
            camera.attachControl(canvas, false);

            BABYLON.SceneLoader.ImportMesh(
               "him", "scenes/Dude/", "Dude.babylon", scene, function (newMeshes, particleSystems, skeletons) {
               var dude = newMeshes[0];
               console.log(dude);
               dude.rotation.y = Math.PI;
               dude.position = new BABYLON.Vector3(0, 0, -80);
               scene.beginAnimation(skeletons[0], 0, 100, true, 1.0);
            })
            return scene;
         };
         var scene = createScene();
         engine.runRenderLoop(function() {
            scene.render();
         });
      </script>
   </body>
</html>

In the above demo link, we have used Dude.babylon mesh. You can download the json file for Dude.babylon from here −

Dude.babylon

Save the file in scenes to get the output as shown below.

Output

The above line of code generates the following output −

Skeletons And Bones

Explanation

For the import mesh, we have used babylonjs dude mesh.

The mesh gives us skeletons. For example, skeleton = skeletons[0];

To get bones from the skeletons, execute the following command −

skeleton.bones; //it gives a array.

In the above demo, we created 2 spheres and passed on to the mesh. For this, we executed the following commands −

sphere.attachToBone(skeleton.bones[30], dude);

And,

sphere1.attachToBone(skeleton.bones[40], dude);

attachToBone is a function wherein, you can give any mesh to the bone.

Skeleton.bones[30] and skeleton.bones[40] refers to the hands of the skeleton.

Advertisements