Thursday, March 14, 2013

Physijs HeightField

‹prev | My Chain | next›

According to my little tag cloud, I have written 48 posts on Physijs. In all those posts and all the research necessary for them, I somehow managed to never come across the HeightField class in the list of supported objects. Thankfully Chandler Prall made mention of them, so now I at least know of their existence. I have absolutely no idea if they will be of any use to me in 3D Game Programming for Kids. There is no way to know unless I take at least a little time to play.

Before I get started, it is worth noting that there is a nifty sample page for HeightField on the physijs site.

I have a simple lights an materials chapter in the book that takes the reader though creating a donut and shadow (and eventually animation):
  var shape = new THREE.TorusGeometry(100, 50, 8, 20);
  var cover = new THREE.MeshPhongMaterial();
  cover.emissive.setRGB(0.8, 0.1, 0.1);
  cover.specular.setRGB(0.9, 0.9, 0.9);
  var donut = new THREE.Mesh(shape, cover);
  scene.add(donut);
  donut.castShadow = true;

  var shape = new THREE.PlaneGeometry(1000, 1000);
  var cover = new THREE.MeshBasicMaterial();
  var ground = new THREE.Mesh(shape, cover);
  ground.position.set(0, -200, 0);
  ground.rotation.set(-Math.PI/2, 0, 0);
  ground.receiveShadow = true;
  scene.add(ground);
A light source and renderer tweaks result in:



To get started with HeightField, I replace the ground that is created from a THREE.Mesh to a Physijs.HieghtField:
  var shape = new THREE.PlaneGeometry(1000, 1000);
  var cover = new THREE.MeshBasicMaterial();
  var ground = new Physijs.HeightfieldMesh(
    shape, cover, 0
  );
  // ...
After making that change, nothing happens. More precisely, nothing changes on the screen—I still have my donut casting a shadow. At least I have not broken anything.

To get height in my height field, I need to change the z value of the vertices in the ground. To achieve smooth bumps in the height field, I divide up the geometry shape into a 50 by 50 grid. Then I work through each vertex in the resultant shape, setting the z value to the cosine of the x position:
  for (var i=0; i<shape.vertices.length; i++) {
    var vertex = shape.vertices[i];
    vertex.z = 10 * Math.cos(vertex.x);
  }
The result is a pretty cool ripple effect in the ground:



So, of course I make that into rolling hills and add controls to the donut to speed about:



Good times.

These height field objects are definitely pretty cool. I am still not sure if I have a good use for them in the book, but I will let the idea percolate for a while. Hopefully I can come up with something...


Day #690

No comments:

Post a Comment