| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970 |
- using UnityEditor.PackageManager.UI;
- using UnityEngine;
- public class TerrainGenerator : MonoBehaviour
- {
- public int height = 5;
- public int length = 1000;
- public int width = 1000;
- public int heightmapResolution = 1025;
- public float hillsRate = 0.5f;
- public float slope = 0.5f;
- public TerrainLayer[] terrainLayers;
- // Start is called once before the first execution of Update after the MonoBehaviour is created
- void Start()
- {
- }
- private void OnEnable()
- {
- var terrain = GetComponent<Terrain>();
- var terrainCollider = terrain.GetComponent<TerrainCollider>();
- var terrainData = new TerrainData()
- {
- size = new Vector3(length, height, width),
- heightmapResolution = heightmapResolution
- };
- var map = new float[terrainData.heightmapResolution, terrainData.heightmapResolution];
- for (int i = 0; i < terrainData.heightmapResolution; i++)
- {
- for (int j = 0; j < terrainData.heightmapResolution; j++)
- {
- var prevHeight = j == 0
- ? i == 0
- ? Random.Range(-slope, slope)
- : map[i - 1, 0]
- : map[i, j - 1];
- var isSlope = Random.value <= hillsRate;
- if (isSlope)
- {
- map[i, j] = Random.Range(-slope, slope); // prevHeight * (1 + Random.Range(-slope, slope));
- }
- else
- {
- map[i, j] = 0;
- }
- }
- }
- terrainData.SetHeights(0, 0, map);
- terrain.terrainData = terrainData;
- terrainCollider.terrainData = terrainData;
- terrainData.terrainLayers = terrainLayers;
- Debug.Log(terrain.terrainData.size);
- }
- // Update is called once per frame
- void Update()
- {
-
- }
- }
|