MapGenerator.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. using UnityEngine;
  2. public class MapGenerator : MonoBehaviour
  3. {
  4. public enum DrawMode { NoiseMap, ColourMap};
  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. }
  44. }
  45. private void OnValidate()
  46. {
  47. if (mapWidth < 1)
  48. {
  49. mapWidth = 1;
  50. }
  51. if (mapHeight < 1)
  52. {
  53. mapHeight = 1;
  54. }
  55. if (lacunarity < 1)
  56. {
  57. lacunarity = 1;
  58. }
  59. if(octaves < 0)
  60. {
  61. octaves = 0;
  62. }
  63. }
  64. }
  65. [System.Serializable]
  66. public struct TerrainType
  67. {
  68. public string name;
  69. public float height;
  70. public Color colour;
  71. }