TerrainGenerator.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using UnityEditor.PackageManager.UI;
  2. using UnityEngine;
  3. public class TerrainGenerator : MonoBehaviour
  4. {
  5. public int height = 5;
  6. public int length = 1000;
  7. public int width = 1000;
  8. public int heightmapResolution = 1025;
  9. public float hillsRate = 0.5f;
  10. public float slope = 0.5f;
  11. public TerrainLayer[] terrainLayers;
  12. // Start is called once before the first execution of Update after the MonoBehaviour is created
  13. void Start()
  14. {
  15. }
  16. private void OnEnable()
  17. {
  18. var terrain = GetComponent<Terrain>();
  19. var terrainCollider = terrain.GetComponent<TerrainCollider>();
  20. var terrainData = new TerrainData()
  21. {
  22. size = new Vector3(length, height, width),
  23. heightmapResolution = heightmapResolution
  24. };
  25. var map = new float[terrainData.heightmapResolution, terrainData.heightmapResolution];
  26. for (int i = 0; i < terrainData.heightmapResolution; i++)
  27. {
  28. for (int j = 0; j < terrainData.heightmapResolution; j++)
  29. {
  30. var prevHeight = j == 0
  31. ? i == 0
  32. ? Random.Range(-slope, slope)
  33. : map[i - 1, 0]
  34. : map[i, j - 1];
  35. var isSlope = Random.value <= hillsRate;
  36. if (isSlope)
  37. {
  38. map[i, j] = Random.Range(-slope, slope); // prevHeight * (1 + Random.Range(-slope, slope));
  39. }
  40. else
  41. {
  42. map[i, j] = 0;
  43. }
  44. }
  45. }
  46. terrainData.SetHeights(0, 0, map);
  47. terrain.terrainData = terrainData;
  48. terrainCollider.terrainData = terrainData;
  49. terrainData.terrainLayers = terrainLayers;
  50. Debug.Log(terrain.terrainData.size);
  51. }
  52. // Update is called once per frame
  53. void Update()
  54. {
  55. }
  56. }