Learning Three.js

or WebGL for Dummies

Perlin Terrain Procedural Generation for Your Game With threex.terrain

This is post is part of the ‘one threex a day’ challenge. This challenge is to publish every day one game extension for three.js! One per day, every day and that for 2month! In this post, we gonna talk about threex.terrain. threex.terrain is a three.js games extension which provides a procedural terrain generated from a simplex noise, the Perlin noise. As you can see you have different zones that make the terrain more varied, the blue zone represents water, the green one represents trees or grass and the white zone at the mountain top is snow. Imagine your video game character walking on these 3D mountains or flying over them, pretty cool eh? You can take him through river, forest, wind and snow if you want ;)

To see the other posts about one threex a day and forget our moto! “A THREEx extension a day, gets your game on its way!”

Show Don’t Tell

How To Install It

You can install it via script tag

1
<script src='threex.terrain.js'></script>

Or you can install with bower, as you wish.

1
bower install threex.terrain

How To Use It

To allocate a heightMap with a width of 100 and a depth of 200, do

1
var heightMap   = THREEx.Terrain.allocateHeightMap(100, 200)

To generate some heights based on a simplex/perlin noise, do

1
THREEx.Terrain.simplexHeightMap(heightMap)

If you want to display it in three.js, built a THREE.PlaneGeometry for it

1
2
3
4
5
6
7
// build the geometry
var geometry    = THREEx.Terrain.heightMapToPlaneGeometry(heightMap)
// init the material
var material    = new THREE.MeshPhongMaterial();
// create the mesh and add it to the scene
var mesh    = new THREE.Mesh( geometry, material );
scene.add( mesh );

To get the ground height of this mesh, use the following

1
var y = THREEx.Terrain.planeToHeightMapCoords(heightMap, mesh, x, z)

It is possible to enhance the rendering of this heightmap with some vertexColor, and a smoother shading if you want.

1
2
3
4
5
6
7
8
9
10
11
12
// build the geometry
var geometry    = THREEx.Terrain.heightMapToPlaneGeometry(heightMap)
// set the vertexColor in the geometry
THREEx.Terrain.heightMapToVertexColor(heightMap, geometry)
// init the material
var material    = new THREE.MeshPhongMaterial({
    shading     : THREE.SmoothShading,
    vertexColors    : THREE.VertexColors,
});
// create the mesh and add it to the scene
var mesh    = new THREE.Mesh( geometry, material );
scene.add( mesh );

To get the height with heightMap coordinates, just use

1
var y   = THREEx.Terrain.heightMapToHeight(heightMap, x, z)

If you want to display the result in a canvas 2d, just do

1
2
var canvas  = THREEx.Terrain.heightMapToCanvas(heightMap)
document.body.appendChild(canvas)

Comments