city-generation/Game/Assets/Scripts/Unity/TerrainGeneratorScript.cs

91 lines
2.1 KiB
C#
Raw Normal View History

2015-03-19 10:34:58 +00:00
using UnityEngine;
using System.Collections;
using TransportGame.Utils;
using System.Threading;
using TransportGame.Generator;
using TransportGame.Model;
using TransportGame.Business;
public class TerrainGeneratorScript : MonoBehaviour
{
private Map map = null;
2015-03-19 10:34:58 +00:00
public int TerrainWidth = 1024;
public int TerrainHeight = 1024;
public GameObject WaterObject;
2015-03-19 10:34:58 +00:00
// Use this for initialization
void Start()
{
StartCoroutine(GenerateMap());
}
2015-03-19 10:34:58 +00:00
private void GenerateTerrainThread()
{
TerrainGenerator generator = new TerrainGenerator();
map = generator.Generate(TerrainWidth, TerrainHeight);
}
2015-03-19 10:34:58 +00:00
private Mesh GenerateWater()
{
Mesh water = new Mesh();
water.name = "water";
water.vertices = new[] {
new Vector3(0, map.WaterLevel, 0),
new Vector3(0, map.WaterLevel, map.Height),
new Vector3(map.Width, map.WaterLevel, 0),
new Vector3(map.Width, map.WaterLevel, map.Height)
};
water.triangles = new[] { 0, 1, 2, 2, 1, 3 };
water.uv = new[] {
new Vector2(0, 0),
new Vector2(0, 1),
new Vector2(1, 0),
new Vector2(1, 1)
};
water.RecalculateNormals();
2015-03-19 10:34:58 +00:00
return water;
}
2015-03-19 10:34:58 +00:00
private IEnumerator GenerateMap()
{
// Wait for the map generation thread
foreach (var i in Task.RunAsync(GenerateTerrainThread))
yield return i;
2015-03-19 10:34:58 +00:00
// Generate terrain data
TerrainData terrainData = new TerrainData();
terrainData.heightmapResolution = Mathf.Max(map.Height, map.Width) + 1;
terrainData.size = new Vector3(map.Width, map.Biome.Height, map.Height);
terrainData.SetDetailResolution(1024, 8);
terrainData.SetHeights(0, 0, map.Heights);
terrainData.name = "Generated Terrain Data";
yield return null;
2015-03-19 10:34:58 +00:00
// Create terrain object
GameObject terrain = Terrain.CreateTerrainGameObject(terrainData);
terrain.name = "Generated Terrain";
yield return null;
2015-03-19 10:34:58 +00:00
Terrain terrainComp = terrain.GetComponent<Terrain>();
terrainComp.heightmapPixelError = 1;
yield return null;
2015-03-19 10:34:58 +00:00
// Set water
if (WaterObject != null)
{
MeshFilter waterMesh = WaterObject.GetComponent<MeshFilter>();
waterMesh.mesh = GenerateWater();
}
// Set up textures
}
2015-03-19 10:34:58 +00:00
// Update is called once per frame
void Update()
{
}
2015-03-19 10:34:58 +00:00
}