I busted tail to attempt some code for my loyal Megabite readers this week, and in the end I decided to scrap it. Why? Well, my idea was to show that Unity was capable of procedural terrain generation on a massive scale (which it is), but what I came up with pales in comparison to what I came across within the Unity Community forum. (link here)
A user by the name of Megaton has not only created an amazing Terrain Generator, but he’s also been kind enough to release it for free (here).
Also, be sure to check it out in your browser here, because it’s hard to explain how amazing it looks live.
So, in this article, I’m going to show a few sections of this very complex piece of code and do what I can to explain how something like this can be accomplished. By comparison, my own little experiment looked far less realistic, and I think I would be doing an injustice for my readers by showing them something like that while knowing this was available to them for free.
The first thing we should look at is the setup of the variables – the ones that control the finer points of generation as a whole and make the world bumpy. The developer who created this project placed these variables inside of a .js sale called “cgame”, and it reads like this:
#pragma strict
class cgame extends UnityEngine.Object {
// Project
var PRODUCT_NAME = "Procedural Terrain Generator";
var PRODUCT_VERSION = "1.0";
// Engine
var GAMESPEED = 1.0;
// Game World
var WORLDSEED = 123;
var WATER_COLOR = Color( 0.5, 0.6, 0.7 );
var TERRAIN_SIZE = 256;
var TERRAIN_GRIDSIZE : float = 200;
var TERRAIN_GRIDVIEW : float = 10;
var TERRAIN_GRIDCOUNT = 100;
var TERRAIN_HEIGHT = 250.0; // default: 200
var TERRAIN_MAX_SUBOBJECTS = 75;
var TERRAIN_PLANE_QUADSIZE = 12.0;
var TERRAIN_GRID_SIZE = 2000;
}
static var gCgame : cgame;
static function InitCgame() {
gCgame = new cgame();
}
You can change the numbers in this section to get some varying results – things are labelled fairly well so theres really no need to go much into detail here. What I will mention about how this script works is that it does continuously generate new terrain meshes that match up to the existing pieces – each has a unique name and they match up fairly well.
The magic of this effect comes from a mixture of scripts, but all seem to be centralized around terrain.js, which contains heading such as:
- GET PLAYERS POSITION ON THE TERRAIN GRID
- IF PLAYER STEPS ONTO A NEW TERRAIN GRID THEN ADD AND REMOVE PLANES
- ADDS PLANES DURING PLAY
- etc.
Each section in this portion of the script is very clearly labeled, and it is a great learning experience for intermediate unity js programmers. I found that for me, working backward from this portion made things more understandable:
//----------------------------------------
// ADDS PLANES DURING PLAY
//----------------------------------------
function TerrDrawRow( position : Vector3, tgF : Vector2, tgT : Vector2 ) {
Math.Floor( tgF );
Math.Floor( tgT );
var gridsize = gCgame.TERRAIN_GRIDSIZE;
while( tgF != tgT ) {
var pos = position;
pos[0] += tgF[0] * gridsize;
pos[2] += tgF[1] * gridsize;
var name = "X" + Mathf.Floor( pos[0] ) + "Z" + Mathf.Floor( pos[2] );
if( !TerrPlaneExists( name ) ) {
TPlaneNames.Add( name );
var plane : Transform = Instantiate( t_plane, pos, Quaternion.identity ) as Transform;
plane.parent = parentObject;
plane.name = name;
var soc : Terrain_Plane = new Terrain_Plane( plane );
terrain_planes.Add( soc );
heightmodqueue.Add( soc );
}
tgF[0] += tgF[0] != tgT[0] ? Mathf.Sign( tgT[0] - tgF[0] ) : 0;
tgF[1] += tgF[1] != tgT[1] ? Mathf.Sign( tgT[1] - tgF[1] ) : 0;
}
}
Of course you do need to bounce around between the various functions, and some are spread across multiple files, but things start clicking into place. This section will add the new terrain objects and name them while attaching them to a parent object. At the same time, it only does so if the name doesn’t already exist.
Admittedly, the author admits that the generation isn’t 100% seamless – in some areas where one grid connects to another, you can literally see the seam where one ends and the next begins. However, it isn’t something that detracts from the overall usefulness of the tool.
If you download and use this yourself on a project, load up the test scene and alter the movement controls of the “player” to allow yourself a high ground/air speed and an increased jumping ability. In doing, you’ll be able to take yourself across the landscape for a very long and scenic ride.

Wow thanks! I really dig your tutorials
Thanks! If theres anything specific you would like to see, lemme know and I’ll give it a shot :)
Thanks wow. I don’t know if it’s too specific, but I’d love to know how to script a player-controlled ship you can walk around while it’s moving (like on autopilot). I’ve been struggling with this and it’s hard to find resources on that particular issue. If you can find a way to generalize it to the principal, that would be sweet too; if its not in your interest, no worries either :) I’m still pretty new to Unity
I’m sure it can be done, though I don’t have any script examples readily available. Right off hand, I would assume that we would want to use some of the nifty rigidbody components that unity has in the menu, or perhaps even using rigidbody.addRelativeForce() on the player while using the existing velocity of the ship within the calculation. That might actually be cool in itself, as you could add in an extra variable for “wind” if the ship is open-air.
I tell ya what – I’ll play with different ideas and see what I can come up with. For now, I will point out that the isKinematic property of the rigidbody component has this definition through the unity docs: “If enabled, the object will not be driven by the physics engine, and can only be manipulated by its Transform. This is useful for moving platforms or if you want to animate a Rigidbody that has a HingeJoint attached.” Perhaps the ship should be kinematic in this instance.
Wicked, again, many appreciations. I’ve been experimenting with rigid body ships and different constraints and forces, it seems with me and enabling physics in particular, things go crazy and fly apart. I haven’t tried a couple things you mention though, so even if it’s not tutorial worthy, you’ve already helped me :D
Hi there! First of all, great stuff!
I was just wondering – how would one go about doing making this procedural terrain into a cube-sphere? I’ve been trying to get “full” scale procedural planets into unity for about a year, but it’s currently way beyond my programming skills to do so.. Would it be possible in some way to deform the mesh in-game (for terraforming, etc.)? What about physics, LOD etc.
Some huge questions, I know.
Thanks for reading!
Well, first and foremost – I love this idea. I can see why something like this would take a long time to figure out – a unity terrain is a flat plane, so giving it a curvature would not be an easy feat.
Only a few things come to mind – but It depends on what you mean by “full scale”. If you’re talking about a planet that is actually the size of a planet, I’m not sure that many computers would easily handle calculations like that. However, like many things in gaming, sometimes we can trick the eye into giving the impression of what we want the user to see, and toward that purpose, the way I might try to go about it would be to apply an x-degree overall tilt to each new piece of terrain after the regular randomizations calculations are done, and then line it up with the neighbor before it. if we just did 1 degree, for example, we’d end up with 360 terrain chunks that formed a giant ring. From there, the could attempt to go about basically emulating what a polygon-based sphere would look like, with each face being a randomized terrain chunk.
While I don’t have experience with it personally, the other option would be to use code to generate your own complete mesh. I can’t speak much on this, but I don know Unity supports it. If you wen’t this route, you’d want to basically start by generating a lower-resolution sphere, and then begin to add points the would be randomized upon starting.
Either way you go about it, it becomes even more difficult when I think about how you would save such a thing to be loaded later, unless what you were going for was meant to be random each and every time.
All this said, I am certainly not a code guru – there are many people out there that have far more skill with this subject, as I fully admit. perhaps someone with experience in this will speak up here – I’d love to see something like this come to life.
It’s not actually very difficult if you’re writing your own engine but there might be some Unity specific problems – such as not being able to use any builtin terrain functions/water/etc.
There’s a good article here: http://britonia.wordpress.com/2010/05/20/planet-geometry/