Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using System.Collections;
- public class TerrainNoise : MonoBehaviour {
- float waterSmooth = 0;
- float[,] heights;
- Terrain terrain;
- TerrainData data;
- Transform water;
- int noiseLayerCount = 20;
- NoiseLayer[] noiseLayers;
- float heightBoost = 10;
- float updateTime;
- bool dirty = true;
- void OnGUI()
- {
- GUILayout.BeginArea( new Rect(20,20,400,400) );
- GUI.color = Color.black;
- GUILayout.Label("WaterSmooth: "+waterSmooth);
- float newWaterSmooth = GUILayout.HorizontalSlider(waterSmooth, 0f, 1f);
- if (newWaterSmooth != waterSmooth)
- {
- waterSmooth = newWaterSmooth;
- dirty = true;
- updateTime = Time.time + 0.5f;
- }
- GUILayout.Label("HeightBoost: "+heightBoost);
- float newHeightBoost = GUILayout.HorizontalSlider(heightBoost, 1f, 40f);
- if (newHeightBoost != heightBoost)
- {
- heightBoost = newHeightBoost;
- dirty = true;
- updateTime = Time.time + 0.5f;
- }
- GUILayout.EndArea();
- }
- void Start()
- {
- terrain = GetComponent<Terrain>();
- data = terrain.terrainData;
- heights = new float[ data.heightmapWidth, data.heightmapHeight];
- water = GameObject.Find ("Water").transform;
- // create the required number of noise layer definitions
- noiseLayers = new NoiseLayer[noiseLayerCount];
- float frequency = .003f;
- float amplitude = 0.5f;
- for( int n=0; n<noiseLayers.Length; ++n)
- {
- noiseLayers[n] = new NoiseLayer();
- noiseLayers[n].frequency = frequency;
- noiseLayers[n].amplitude = amplitude;
- amplitude *= 0.5f;
- frequency *= 2f;
- }
- }
- // Use this for initialization
- void Update () {
- if (dirty && Time.time > updateTime)
- {
- float waterHeight = water.position.y / data.size.y;
- for( int x=0; x< data.heightmapWidth; ++x)
- {
- for( int z=0; z< data.heightmapHeight; ++z)
- {
- // accumulate height values from each perlin noise layer
- float height = 0;
- foreach(NoiseLayer noiseLayer in noiseLayers)
- {
- float f = noiseLayer.frequency;
- float a = noiseLayer.amplitude;
- height += Mathf.PerlinNoise(x*f, z*f) * a;
- }
- // smooth heights at water level
- float waterSmoothedHeight = height - waterHeight;
- float heightSign = Mathf.Sign(waterSmoothedHeight);
- waterSmoothedHeight *= (waterSmoothedHeight * heightSign) * heightBoost;
- waterSmoothedHeight += waterHeight;
- height = Mathf.Lerp( height, waterSmoothedHeight, waterSmooth );
- heights[x,z] = height;
- }
- }
- data.SetHeights(0, 0, heights);
- dirty = false;
- }
- }
- }
- public struct NoiseLayer
- {
- public float amplitude;
- public float frequency;
- }
Advertisement
Add Comment
Please, Sign In to add comment