MapGenerator.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. using UnityEngine;
  2. using System.Collections;
  3. using System;
  4. public class MapGenerator : MonoBehaviour
  5. {
  6. public int width;
  7. public int height;
  8. public string seed;
  9. public bool useRandomSeed;
  10. [Range(0, 100)]
  11. public int randomFillPercent;
  12. int[,] map;
  13. void Start()
  14. {
  15. GenerateMap();
  16. }
  17. void Update()
  18. {
  19. if (Input.GetMouseButtonDown(0))
  20. {
  21. GenerateMap();
  22. }
  23. }
  24. void GenerateMap()
  25. {
  26. map = new int[width, height];
  27. RandomFillMap();
  28. for (int i = 0; i < 5; i++)
  29. {
  30. SmoothMap();
  31. }
  32. MeshGenerator meshGen = GetComponent<MeshGenerator>();
  33. meshGen.GenerateMesh(map, 1);
  34. }
  35. void RandomFillMap()
  36. {
  37. if (useRandomSeed)
  38. {
  39. seed = Time.time.ToString();
  40. }
  41. System.Random pseudoRandom = new System.Random(seed.GetHashCode());
  42. for (int x = 0; x < width; x++)
  43. {
  44. for (int y = 0; y < height; y++)
  45. {
  46. if (x == 0 || x == width - 1 || y == 0 || y == height - 1)
  47. {
  48. map[x, y] = 1;
  49. }
  50. else
  51. {
  52. map[x, y] = (pseudoRandom.Next(0, 100) < randomFillPercent) ? 1 : 0;
  53. }
  54. }
  55. }
  56. }
  57. void SmoothMap()
  58. {
  59. for (int x = 0; x < width; x++)
  60. {
  61. for (int y = 0; y < height; y++)
  62. {
  63. int neighbourWallTiles = GetSurroundingWallCount(x, y);
  64. if (neighbourWallTiles > 4)
  65. map[x, y] = 1;
  66. else if (neighbourWallTiles < 4)
  67. map[x, y] = 0;
  68. }
  69. }
  70. }
  71. int GetSurroundingWallCount(int gridX, int gridY)
  72. {
  73. int wallCount = 0;
  74. for (int neighbourX = gridX - 1; neighbourX <= gridX + 1; neighbourX++)
  75. {
  76. for (int neighbourY = gridY - 1; neighbourY <= gridY + 1; neighbourY++)
  77. {
  78. if (neighbourX >= 0 && neighbourX < width && neighbourY >= 0 && neighbourY < height)
  79. {
  80. if (neighbourX != gridX || neighbourY != gridY)
  81. {
  82. wallCount += map[neighbourX, neighbourY];
  83. }
  84. }
  85. else
  86. {
  87. wallCount++;
  88. }
  89. }
  90. }
  91. return wallCount;
  92. }
  93. }