Friday, July 13, 2012

Shifting Frame of Reference in Gladius

‹prev | My Chain | next›

Up tonight, I hope to get the legs on my Gladius avatar moving. I have a rudimentary avatar assembled:


To rotate the leg, I need to add a game task() to the existing game code:
      var engine = new Gladius();

      // CubicVR rendering backend...
      // Mesh and material resources...

      engine.resume();
      game(engine, resources);

      function game(engine, resources) {
        var math = engine.math;
        var space = new engine.SimulationSpace();
        // Setup space...

        var task = new engine.FunctionTask( function() {
          var transform = space.findNamed("right-leg").findComponent("Transform")
            , rotation = new engine.math.Vector3(transform.rotation);

          rotation = engine.math.vector3.add(rotation, [0, 0, space.clock.delta * 0.001]);
          transform.setRotation(rotation);

        });
        task.start();
The result is that leg spins around its middle:


Ugh. To get the rotation around the end of the leg instead of the middle means a separate frame of reference. I can rotate the frame of reference and place the leg appropriately in this new frame of reference.

So I add the frame of reference to the right and slightly down from the center of the body:
        space.add(new engine.Entity("right-leg-frame",
          [
            new engine.core.Transform([0.5, -0.5, 0])
          ],
          ["avatar"],
          space.findNamed("body")
        ));
Then, instead of adding the right leg to the body's frame of reference, I add it to this "right-leg-frame", shifting it down so the end of the leg aligns with the start of "right-leg-frame":
        space.add(new engine.Entity("right-leg",
          [
            new engine.core.Transform([0, -1, 0]),
            new cubicvr.Model(resources.cylinder_mesh, resources.blue_material)
          ],
          ["avatar"],
          space.findNamed("right-leg-frame")
        ));
Lastly, I set the game task() to rotate "right-leg-frame" instead of the right leg itself:
        var task = new engine.FunctionTask( function() {
          var entity = space.findNamed("right-leg-frame")
            , transform = entity.findComponent("Transform")
            , rotation = new engine.math.Vector3(transform.rotation);

          rotation = engine.math.vector3.add(rotation, [0, 0, space.clock.delta * 0.001]);
          transform.setRotation(rotation);

        });
With that, my leg now remains firmly attached to the body:


Of course, it stays firmly attached as it moves 360° around, but I will worry about that another day.


Day #446

No comments:

Post a Comment