Search Unity

Terrain data???

Discussion in 'Scripting' started by EnsurdFrndship, Jul 25, 2014.

  1. EnsurdFrndship

    EnsurdFrndship

    Joined:
    Apr 17, 2010
    Posts:
    786
    Hello,
    I was wondering if there is a way I can attach a script to my terrain and create a script that reduces the height of my terrain by script (causing the mountains and valleys to eventually become flat planes). I checked the documentation on TerrainData, have the latest version of Unity3D, but it still doesn't recognize half the functions documented (such as heightmapHeight).

    Thank you,
    Michael S. Lowe
     
  2. ensiferum888

    ensiferum888

    Joined:
    May 11, 2013
    Posts:
    317
    Hey there,

    You're looking at the SetHeights() function to set a specific height. A heightMap simply is a 2D grayscale texture where each pixel represents the height (from 0 = black to 255 = white) of your terrain. These are normalized so say you put the MaxHeight of your terrain at 100. A pixel that's white represents 100% of your height therefore 100 units whereas a pixel that's gray (128 or 0.5 normalized) represents 50% of your height therefore 50 units high.

    heightMapHeight represents the height, in pixels of your heightMap. The Scripting API used to be more descriptive but generally speaking this is how you would use it:

    Code (CSharp):
    1.  
    2. TerrainData tData = Terrain.activeTerrain.TerrainData;
    3.  
    4. float[,] heights = tData.GetHeights(0,0, tData.heightMapWidth, tData.heightMapHeight);
    5.  
    6. for(int k = 0 ; k < tData.heightMapHeight ; k++){
    7.     for(int i = 0 ; i < tData.heightMapWidth ; i++){
    8.         if(heights[i,k] > maxHeight){
    9.             height[i,k] = maxHeight;
    10.         }
    11.     }
    12. }    
    13. tData.SetHeights(0, 0, heights);
    14.  
    Noticed I inverted the height and the width in the 2 for loops, for some reason GetHeights returns the array as [height, width] instead of [width, height].

    GetHeights takes 4 arguments: the X position on your terrain, the Y position on your terrain and the width and height of the sample you want to take. For example there are some cases where you'd only want a 10 x 10 height sample on your terrain rather than the entire map.

    It returns a float[height, width] that contains the height of your current position. (I don't remember if the height value is in units or normalised to the maxHeight of the terrain itself though.

    Keep in mind that SetHeights can be slow on large terrains so don't call it too often!
     
  3. EnsurdFrndship

    EnsurdFrndship

    Joined:
    Apr 17, 2010
    Posts:
    786
    Thank you.
     
  4. Sheikh_Ali

    Sheikh_Ali

    Joined:
    Jun 19, 2019
    Posts:
    2
    Kindly tell me if i can get painted grass value in terrain.Can I?