MapGenerator.cs 2.2 KB

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