MapGenerator.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using UnityEngine;
  2. public class MapGenerator : MonoBehaviour
  3. {
  4. public enum DrawMode { NoiseMap, ColourMap, Mesh};
  5. public DrawMode drawMode;
  6. public const int mapChunkSize = 241;
  7. [Range(0,6)]
  8. public int levelOfDetail;
  9. public float noiseScale;
  10. public int octaves;
  11. [Range(0,1)]
  12. public float persistance;
  13. public float lacunarity;
  14. public int seed;
  15. public Vector2 offset;
  16. public float MeshHeightMultiplier;
  17. public AnimationCurve meshHeightCurve;
  18. public bool autoUpdate;
  19. public TerrainType[] regions;
  20. public void GenerateMap()
  21. {
  22. float[,] noiseMap = Noise.GenerateNoiseMap(mapChunkSize, mapChunkSize, seed, noiseScale, octaves, persistance, lacunarity, offset);
  23. Color[] colourMap = new Color[mapChunkSize * mapChunkSize];
  24. for(int y=0; y<mapChunkSize; y++)
  25. {
  26. for (int x=0; x<mapChunkSize; x++)
  27. {
  28. float currentHeight = noiseMap[x, y];
  29. for (int i = 0; i < regions.Length; i++)
  30. {
  31. if(currentHeight <= regions[i].height)
  32. {
  33. colourMap[y*mapChunkSize + x] = regions[i].colour;
  34. break;
  35. }
  36. }
  37. }
  38. }
  39. MapDisplay display = FindFirstObjectByType<MapDisplay>();
  40. if(drawMode == DrawMode.NoiseMap)
  41. {
  42. display.DrawTexture(TextureGenerator.TextureFromHeightMap(noiseMap));
  43. } else if (drawMode == DrawMode.ColourMap)
  44. {
  45. display.DrawTexture(TextureGenerator.TextureFromColourMap(colourMap, mapChunkSize, mapChunkSize));
  46. }else if(drawMode == DrawMode.Mesh)
  47. {
  48. display.DrawMesh(MeshGenerator.GenerateTerrainMesh(noiseMap, MeshHeightMultiplier, meshHeightCurve, levelOfDetail), TextureGenerator.TextureFromColourMap(colourMap, mapChunkSize, mapChunkSize));
  49. }
  50. }
  51. private void OnValidate()
  52. {
  53. if (lacunarity < 1)
  54. {
  55. lacunarity = 1;
  56. }
  57. if(octaves < 0)
  58. {
  59. octaves = 0;
  60. }
  61. }
  62. }
  63. [System.Serializable]
  64. public struct TerrainType
  65. {
  66. public string name;
  67. public float height;
  68. public Color colour;
  69. }