Generating terrain meshes programmatically is the first step toward building procedural worlds. Instead of hand-modeling a landscape, we generate a grid of vertices and “displace” them using a heightmap or noise.
A terrain mesh is a 2D grid of vertices. For a $10 \times 10$ terrain “quad,” we need $11 \times 11$ vertices to close the loops.
[0, 1, 11] and [1, 12, 11]).The $y$ value of each vertex is determined by:
void CreateMesh() {
vertices = new Vector3[(xSize + 1) * (zSize + 1)];
for (int i = 0, z = 0; z <= zSize; z++) {
for (int x = 0; x <= xSize; x++) {
float y = Mathf.PerlinNoise(x * .3f, z * .3f) * 2f;
vertices[i] = new Vector3(x, y, z);
i++;
}
}
// ... Triangle and Normal generation ...
}
Lighting requires accurate surface normals. For procedural terrain, don’t rely on the engine’s default calculator.
Rendering a massive $4096 \times 4096$ grid as a single mesh will kill performance.