Wednesday, March 27, 2013

Bonus Points

‹prev | My Chain | next›

Up tonight, I switch back to the river rafting game that seems to be consuming more and more pages in 3D Game Programming for Kids. It has gotten so big that I think that some of it will have to be optional suggestions for game additions. One of the suggestions will be adding elements in the river that add points or remove points if the raft scoops them up.

I think that I know how to do this. I need to add the items to the river after each game reset. When the raft collides with one of these elements, I need to remove them immediately to count points and to prevent them from affecting the motion of the raft.

I start with a reset function for the bonus items, which will remove any existing items and add new ones:
  var bonus_items;
  function resetBonusItems(ground) {
    if (!bonus_items) bonus_items = [];
    removeBonusItems();
    addBonusItems(ground);
  }
I remove the items by removing them from the Three.js / Physi.js scene:
  function removeBonusItems() {
    bonus_items.forEach(function(item) {
      scene.remove(item);
    });
    bonus_items = [];    
  }
Add items is a matter of randomly grabbing the location of the fruit from the river. This is not trivial, but not too hard for a reader that has made it to this chapter in the book:
  function addBonusItems(ground) {
    var points = ground.river_points,
        number_between_90_and_100 = Math.floor(90 + 10*Math.random()),
        number_between_40_and_50 = Math.floor(40 + 10*Math.random());
    bonus_items.push(addFruitPowerUp(points[number_between_90_and_100], ground));
  }
Finally, the add fruit power-up function should look something like:
  function addFruitPowerUp(location, ground) {
    var mesh = new Physijs.ConvexMesh(
      new THREE.SphereGeometry(10),
      new THREE.MeshPhongMaterial({emissive: 0xbbcc00}),
      0
    );
    mesh.receiveShadow = true;
    mesh.position.copy(location)
    scene.add(mesh);
    
    return mesh;
  }
Except that does not work. The river points are in their own frame of reference whereas I am trying to place the fruit bonus item in world coordinates.

Dang.

I may be in trouble here. Bonus items really need to reset after each game, but I cannot add them to an already in-place Phyis.js item — once a Physi.js item is part of the scene, anything that is added to it will not register as a physical object.

My only recourse would be to manually convert from local river frame of reference to world coordinates. I know how to do that, but had meant to avoid including that in the book. Bother.

I call it a night here and will ruminate on how to best tackle this tomorrow. Shame. I really thought that I knew how to do this.

Day #703

1 comment: