Skip to content

Instantly share code, notes, and snippets.

@JonRurka
Last active August 29, 2015 14:15
Show Gist options
  • Save JonRurka/22164bc33919e386bf57 to your computer and use it in GitHub Desktop.
Save JonRurka/22164bc33919e386bf57 to your computer and use it in GitHub Desktop.
public IEnumerator AddTrees()
{
ClearTrees();
int height = _terrain.terrainData.heightmapWidth;
int width = _terrain.terrainData.heightmapWidth;
float[,] heights = _terrain.terrainData.GetHeights(0, 0, width, height);
float[, ,] map = _terrain.terrainData.GetAlphamaps(0, 0, width - 1, height - 1);
Perlin perlin = new Perlin();
perlin.Seed = seed;
Noise2D noisePlane = new Noise2D(width, height, perlin);
noisePlane.GeneratePlanar(0, 1, 0, 1);
float[,] noiseData = noisePlane.GetData();
System.Random rand = new System.Random(seed);
int treesThisFrame = 0;
int totalTrees = 0;
trees = new List<Vector3>();
for (int x = 0; x < width - 1; x++)
{
for (int y = 0; y < height - 1; y++)
{
float Locheight = heights[x, y];
float mapVal = map[y, x, 0];
float noiseVal = noiseData[x, y];
/*if (x == y)
{
Vector3 treePos = new Vector3(x / (float)width, 0, y / (float)height);
TreeInstance ti = new TreeInstance();
ti.prototypeIndex = 0;
ti.heightScale = 1.0f;
ti.widthScale = 1.0f;
ti.color = Color.white;
ti.position = new Vector3(x / (float)width, 0, y / (float)height);
_terrain.AddTreeInstance(ti);
trees.Add(treePos);
treesThisFrame++;
totalTrees++;
}*/
if (mapVal == 1)
{
int treeScarcity = 100;
if (noiseVal >= 0 && noiseVal <= 1)
{
treeScarcity = 80;
}
else if (noiseVal >= 1 && noiseVal <= 2)
{
treeScarcity = 85;
}
else
{
treeScarcity = 90;
}
if (rand.Next(0, 100) >= treeScarcity)
{
TreeInstance ti = new TreeInstance();
ti.prototypeIndex = 0;
ti.heightScale = 1.0f;
ti.widthScale = 1.0f;
ti.color = Color.white;
ti.position = new Vector3(x / (float)width, 0, y / (float)height);
_terrain.AddTreeInstance(ti);
treesThisFrame++;
totalTrees++;
}
}
}
if (x % 10 == 0)
{
Debug.Log("Added " + treesThisFrame + " trees this frame.");
treesThisFrame = 0;
yield return new WaitForEndOfFrame();
}
}
Debug.Log("Added " + totalTrees + " trees in total.");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment