Saturday, February 9, 2013

Shaking Things Up with Random

‹prev | My Chain | next›

I think that I am closing in on a solid, but gentle, object-oriented approach to the latest game in 3D Game Programming for Kids. I still need to extract the simplistic mouse event library that I wrote for Three.js / Physijs objects in the game, but this can wait. For now, I would like to explore adding depth to the game.

There is not actual depth in the game, it is a two dimensional puzzle game. The object is to place ramps so that the player can reach a goal:


The depth that I would like to add tonight involves randomization so that it is not always the same game. Randomizing the placement and orientation of the ramps is fairly easy. I will have to introduce a plus-minus randomizer along the lines of:
  function randomPlusMinus() {
    return 1 - 2*Math.random();
  }
I cannot think of an easier way to do this off the top of my head. It will take a paragraph or two of explanation. It seems a simple concept, but it is probably worth it in the book.

Along those lines, it is probably a good idea to randomize the placement of the goal. I may try to ramdomly place it at the stop of the screen—in either corner or exactly in the middle (width and height refer to the size of the window):
  var x = 0,
     rand = Math.random();
  if (rand < 0.33) x = width / -2;
  if (rand > 0.66) x = width / 2;
  goal.position.set(x, height/2, 0);
  scene.add(goal);
I add an obstacle to the center of the screen to make the game a bit more challenging. The last thing that I do is randomly choose the shape of the ramps. Instead of simply sticking with rectangles, I randomly choose between rectangles and triangles (made with the all-purpose cylinder):
  var ramp = {
    startAt: function(location) {
      var shape = (Math.random() < 0.5) ?
        new THREE.CylinderGeometry(5, height * 0.05, height * 0.5):
        new THREE.CubeGeometry(height * 0.05, height * 0.5, 10);
        
      this.mesh = new Physijs.ConvexMesh(
        shape,
        Physijs.createMaterial(
          new THREE.MeshBasicMaterial({color:0x0000cc}), 0.2, 1.0
        ),
        0
      );
      // ...
    },
    // ...
  };
With that, I think that I have a game that is a little more challenging:


That may do it for this game. I may add some instructions, a timer or a move-to-the-next level. I may also need to decrease the speed with which the player can move as the game is still a little on the easy side. But as-is, this seems fairly solid addition to the book with plenty to offer by way of object lessons.

(live code of the game so far)

Day #657

No comments:

Post a Comment