Friday, March 15, 2013

Playing Nice with Physijs Height Fields

‹prev | My Chain | next›

Up today I would like build on my Physijs height field work from yesterday. I still do not know if they will make a good fit for 3D Game Programming for Kids, but they are interesting enough to warrant another play date.

I have a simple, wavy height field for my donut / raft to play in:

I would like to see if I can add a material that is a bit more realistic. I would also like to see if I can add Physijs material in between the waves so that the bottom of the waves are covered. I start with the latter because I am curious to see if I can “dig” out a trench in a height field mesh to make a river—a key component in the last game that I want in the book.

So I add water:
  var water = new Physijs.ConvexMesh(
    new THREE.PlaneGeometry(1000, 1000),
    new THREE.MeshBasicMaterial({color: 0x0000bb})
  water.rotation.x = -Math.PI/2;
  water.position.y = -100;
  water.receiveShadow = true;
And it just works:

The other thing that I hope to understand tonight is why my hills are a little dull. On the one hand, they are grassy hills—it is not as if they should be very shiny. On the other hand, there should be a little shading given that the material used is a MeshPhongMaterial:
  var shape = new THREE.PlaneGeometry(1000, 1000, 100, 100);
  var cover = new THREE.MeshPhongMaterial();
  cover.emissive.setRGB(0.1, 0.6, 0.1);
  cover.specular.setRGB(0.2, 0.2, 0.2);
  // ...
  var ground = new Physijs.HeightfieldMesh(
    shape, cover, 0
My problem turns out to be in the elided code which sets the height field's height:
  for (var i=0; i<shape.vertices.length; i++) {
    var vertex = shape.vertices[i];
    vertex.z = 25 * Math.cos(vertex.x/40);
After mucking with the vertices height like this, I need to tell Three.js to recompute normals:
  for (var i=0; i<shape.vertices.length; i++) {
    var vertex = shape.vertices[i];
    vertex.z = 25 * Math.cos(vertex.x/40);
And, just like that, I have some decent shading on my hills:

These height maps definitely seem promising. Up tomorrow, I will see if I can figure out how to dig winding paths through them. The nature of the shape vertices makes this seem like a non-trivial problem. If I can solve it, then I just might have the setting for the river rafting game in the last chapter.

Day #691

No comments:

Post a Comment