/// <summary> /// Add a lake to the terrain /// </summary> private void AddLake(Terrain terrain, int tileX, int tileZ, int lakeSize = 150) { var data = terrain.terrainData; //Access height map var width = data.heightmapWidth; var height = data.heightmapHeight; var heightmap = data.GetHeights(0, 0, width, height); //random X and Z coordinate and sample height Vector3 lakeCenter = terrain.RandomPositionOnTerrain(lakeSize); var lakeRadius = lakeSize / 2; var coords = terrain.WorldToTerrainMapCoordinates(lakeCenter); int xCenter = (int)coords.x; int zCenter = (int)coords.z; var minDepth = 0.09f; for (int x = xCenter - lakeRadius; x < xCenter + lakeRadius; x++) { for (int z = zCenter - lakeRadius; z < zCenter + lakeRadius; z++) { //deeper the closer to the center float centerX = 1 - Math.Abs((float)(xCenter - x) / lakeRadius); float centerZ = 1 - Math.Abs((float)(zCenter - z) / lakeRadius); float avg = (centerX * centerZ) / 2; var depth = minDepth * avg; Mathf.Clamp(depth, minDepth - 0.01f, minDepth + 0.01f); heightmap[z, x] -= depth; } } //Update height map data.SetHeights(0, 0, heightmap); lakeCenter.y -= 4.5f; var waterInstance = (GameObject)GameObject.Instantiate(_terrainSettings.WaterPrefab, lakeCenter, Quaternion.identity); waterInstance.SetParent(terrain.gameObject); }