Object Terrain Blending

I was inspired by this Reddit post, that we can read the terrain height map to detect the position of the object/foliage on the terrain and blend the terrain’s texture with it. 


Two main steps achieve the outcome:

  • Detect the contact area between the object/foliage and the terrain.
  • Assign the terrain’s texture to the object/foliage.

  • Retrieve the height map data first. A height map is a grayscale image that encodes the terrain’s shape by assigning elevation values to each grid point. Unity’s API grants access to this height map through scripting; increasing its resolution improves the results.


    Aligning the foliage with the terrain’s coordinate system is crucial because the terrain may be offset from the origin. Since the height map is stored as a texture with values normalized to the [0,1] range, the terrain’s world positions also need to be scaled into that range. Extract the xz components of the object’s world position (A) and the terrain’s world position (B). Subtracting B from A yields a relative vector (C). Dividing C by the terrain’s size normalizes the coordinates into the [0,1] range, providing the correct UV coordinates for sampling the height map.


    Using these UV coordinates, sample the height map and employ a shader function (Unity’s UnpackHeightmap) to decode the height information. Compare the object’s Y position with the sampled terrain height to identify the contact area. Multiplying the terrain’s height by the unpacked height map value correctly scales the elevation so that texture blending occurs over the proper range.


    Final adjustments are customizable; incorporating additional operations (using float and divide nodes) enables refinement of the blend area for a more natural transition.

    Script for reading the terrain data

    We have successfully processed the height map and got the connect range. We can now apply the textures of the terrain to the range. 


    On top of texture blends functions, I built the function for faster terrian texture adjustments and replacement. In the default terrain texture creation, we need to 

    Using Format