Search code examples
c#unity-game-engineterrainunity3d-terrain

Terrain tree instances cannot be set correctly


Im currently experimenting with Terrain trees but im stuck at manipulating their position. The following script as far as i know should work, it also transforms the position into local terrain coordinates yet nothing happens.

private void SetTrees()
{
    var Trees_On_Terrain = Terrain.activeTerrain.terrainData.treeInstances;
    for (int i = 0; i < Trees_On_Terrain.Length; i++)
    {
       Trees_On_Terrain[i].position = new Vector3(10f / 
       Terrain.activeTerrain.terrainData.heightmapResolution, 0f, 10f / 
       Terrain.activeTerrain.terrainData.heightmapResolution);
    }
    Terrain.activeTerrain.terrainData.SetTreeInstances(Trees_On_Terrain, true);
}

They are put into a near the (0,0,0) coordinate.

Please help!


Solution

  • The problem here is that you are dividing your x and y coordiantes with Terrain.activeTerrain.terrainData.heightmapResolution which is not correct.

    Imagine your terrain heightmap resolution is 2049(power of two + 1), but your terrain dimension is 1250 * 500. You still gonna divide x and y by 2049 but you should rather by 1250 and 500.

    You should use the sampled data

    Terrain.activeTerrain.terrainData.heightmapWidthfor the x coordinate Terrain.activeTerrain.terrainData.heightmapHeight for the y coordinate.

    Corrected code snippet:

    private void SetTrees()
    {
       var Trees_On_Terrain = Terrain.activeTerrain.terrainData.treeInstances;
       for (int i = 0; i < Trees_On_Terrain.Length; i++)
       {
          Trees_On_Terrain[i].position = new Vector3(10f / Terrain.activeTerrain.terrainData.heightmapWidth, 0f, 10f / Terrain.activeTerrain.terrainData.heightmapHeight);
       }
       Terrain.activeTerrain.terrainData.SetTreeInstances(Trees_On_Terrain, true);
    }