Question by
Piijas · Jun 21, 2017 at 09:59 AM ·
c#terraindataterrain generation
How to auto-generate a terrain in Unity ?
Hello,
(First of all, I know, I don't have a very good english, sorry ^^')
I'm trying to generate a virtual environment for an experiment, and I have some trouble with the functions I have to use. I try to generate a sinusoidal terrain, with tree on it, but I don't really understand how works the height functions on unity, despite of the different posts I found on the forum. I don't succeed in synchronizing the variations of my ground and the trees that I want to put on it (I always have some trees which are half on the ground). Can you explain me what I'm doing wrong ?
(NB.: I want to put my trees randomly on the ground)
Thanks :)
My code : using System.Collections; using System.Collections.Generic; using UnityEngine;
public class modTerrain : MonoBehaviour {
private static int heightMapWidth = 4048;
private static int heightMapHeight = 4048;
int plop = 0;
float terrainX;
float terrainZ;
Terrain[] listTerrain;
public GameObject theTree;
public float[,] tableauMCoordMap = new float[heightMapWidth, heightMapHeight];
// Use this for initialization
void Start () {
// Loading of the trees' texture
GameObject newTree = (GameObject)Resources.Load("Broadleaf_Desktop");
// Preparation for the generation of the ground
GameObject terrainGameObject = new GameObject();
TerrainData terrainData = new TerrainData();
terrainGameObject = Terrain.CreateTerrainGameObject(terrainData);
GameObject ingameTerrainGameObject = (GameObject)Instantiate(terrainGameObject, new Vector3(), Quaternion.identity);
terrainData.heightmapResolution = 4049;
// Preparation of the matrix containing the relief of the ground
float[,] heightData = new float[heightMapWidth, heightMapHeight];
for (int x = 0; x < heightMapWidth; x++)
{
for (int y = 0; y < heightMapHeight; y++)
{
heightData[x, y] = 0.11f*(float)System.Math.Sin((double)x/42)+0.09f;
// Matrix for other scripts
tableauMCoordMap[x,y] = 100* 0.11f * (float)System.Math.Sin((double)x / 42) + 0.09f;
}
}
terrainData.SetHeights(0, 0, heightData);
terrainData.size = new Vector3(heightMapWidth, 100f, heightMapHeight);
terrainData.SetHeights(0, 0, heightData);
// Texture of the ground
SplatPrototype[] terrainTexture = new SplatPrototype[1];
terrainTexture[0] = new SplatPrototype();
terrainTexture[0].texture = (Texture2D)Resources.Load("diffuse");
terrainData.splatPrototypes = terrainTexture;
// Trees - plop = number of trees
for (plop = 0; plop < 15000; plop++)
{
int a = Random.Range(0, heightMapWidth);
int b = Random.Range(0, heightMapHeight);
Vector3 worldTreePos = new Vector3(b, 100 * heightData[a, b], a);
Instantiate(newTree, worldTreePos, Quaternion.identity);
}
}
// Update is called once per frame
void Update () {
}
}
Comment