Skip to content

Instantly share code, notes, and snippets.

@psema4
Forked from Coac/TerrainGenerator.cs
Created September 1, 2016 03:59
Show Gist options
  • Save psema4/f25e2e23aaa64a93bca847220bb6bc61 to your computer and use it in GitHub Desktop.
Save psema4/f25e2e23aaa64a93bca847220bb6bc61 to your computer and use it in GitHub Desktop.
A basic procedural terrain generation make in Unity3D
using UnityEngine;
using System.Collections;
public class TerrainGenerator : MonoBehaviour {
public Texture2D grassTexture;
public Texture2D rockTexture;
void Start()
{
for (int X = 0; X < 10; X++)
{
for (int Z = 0; Z < 10; Z++)
{
new TerrainChunk(X, Z, grassTexture, rockTexture);
}
}
}
}
public class TerrainChunk
{
private static int HeightmapResolution = 128 + 1;
private static int AlphamapResolution = 128 + 1;
private static int Length = 400;
private static int Height = 400;
private int X = 0;
private int Z = 0;
public TerrainChunk(int X, int Z, Texture2D FlatTexture, Texture2D SteepTexture)
{
this.X = X;
this.Z = Z;
var terrainData = new TerrainData();
terrainData.heightmapResolution = HeightmapResolution;
terrainData.alphamapResolution = AlphamapResolution;
terrainData.SetHeights(0, 0, getHeightmap());
terrainData.size = new Vector3(Length, Height, Length);
addTextures(terrainData, FlatTexture, SteepTexture);
var newTerrainGameObject = Terrain.CreateTerrainGameObject(terrainData);
newTerrainGameObject.transform.position = new Vector3(X * Length, 0, Z * Length);
}
private void addTextures(TerrainData terrainData, Texture2D grassTexture, Texture2D rockTexture)
{
var grassSplat = new SplatPrototype();
var rockSplat = new SplatPrototype();
grassSplat.texture = grassTexture;
rockSplat.texture = rockTexture;
terrainData.splatPrototypes = new SplatPrototype[]
{
grassSplat,
rockSplat
};
terrainData.RefreshPrototypes();
var splatMap = new float[terrainData.alphamapResolution, terrainData.alphamapResolution, 2];
for (var zRes = 0; zRes < terrainData.alphamapHeight; zRes++)
{
for (var xRes = 0; xRes < terrainData.alphamapWidth; xRes++)
{
var normalizedX = (float)xRes / (terrainData.alphamapWidth - 1);
var normalizedZ = (float)zRes / (terrainData.alphamapHeight - 1);
var steepness = terrainData.GetSteepness(normalizedX, normalizedZ);
var steepnessNormalized = steepness / 90f;
splatMap[zRes, xRes, 0] = 1f - steepnessNormalized;
splatMap[zRes, xRes, 1] = steepnessNormalized;
}
}
terrainData.SetAlphamaps(0, 0, splatMap);
}
private float[,] getHeightmap()
{
var heightmap = new float[HeightmapResolution, HeightmapResolution];
for (var zRes = 0; zRes < HeightmapResolution; zRes++)
{
for (var xRes = 0; xRes < HeightmapResolution; xRes++)
{
var xCoordinate = X + (float)xRes / (HeightmapResolution - 1);
var zCoordinate = Z + (float)zRes / (HeightmapResolution - 1);
heightmap[zRes, xRes] = Mathf.PerlinNoise(xCoordinate, zCoordinate);
}
}
return heightmap;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment