Daniel Farrell

Web UI/UX Design & Development
Procedural Generation: Terrain
Classic Tank Game
I have always had an interest in game development as a hobby, but always found it difficult to find where to start and overcome the steep learning curve. Instead, the recent release of No Man's Sky inspired me to focus on the Procedural Generation aspect of game development. I decided to generate a 2D landscape , that could be used for a game such as the classic turn-based tank games. The generator uses JavaScript and the Canvas 2D API to generate and draw the terrain.


I begin by creating a JavaScript object representing a line. The line has a starting (X, Y) position and a destination (X, Y) position.

function Line(sX, sY, dX, dY){
return {
sX: sX,
sY: sY,
dX: dX,
dY: dY
};
}


The terrain is simply an array of lines which join up together to create a gap-less jagged line across the canvas. The first step is to create an empty array to store the lines using var lines = [];, then push the first line to the array using lines.push(Line(0, canvas.height / 2, canvas.width, canvas.height / 2));. This results in a horizontal line across the center of the canvas.

Drawing the first line

The next step is to split this line in half. This is done by adding the sX (startX) position and the dX (destinationX) position of the line together then dividing it by two, and doing the same with the Y positions of the line. Two new lines are created; the first has the same sX and sY as the original but the dX and dY become the calculated half-way point, and the second has the same dX and dY as the original but the sX and sY are the calculated half-way point. At this point, nothing has changed visually, just what was before one line is now two lines. The final part is to add/subtract a random Y value to the connecting point of the two new lines. The range of the random value depends on how varied you want the terrain to be - a high random range may result in a terrain with a large hill or valley, while a small random range results in a rather flat landscape. The initial range I use is 200, meaning a number between -100 and 100 is added to the mid-point of the lines.

Splitting the line

The final step is to repeat the previous step multiple times - the more times you repeat it, the more detailed the terrain becomes. In the animated gif below, I repeat the process 6 times to create the terrain I want.

Generating the terrain

Links

View the demo.
View the source code.