I would like to get the position of trees (TreeInstance) on the terrain. I have the following code that I use but the position of the tree is not correct.
foreach (var treeInstance in terrainData.treeInstances)
{
resourcePositions.Add(treeInstance.position);
}
CodePudding user response:
The TreeInstance position is actually related to the height map of the terrain. To convert it to the world position you should do the following:
foreach (var treeInstance in terrainData.treeInstances)
{
var treeInstancePos = treeInstance.position;
var localPos = new Vector3(treeInstancePos.x * terrainData.size.x, treeInstancePos.y * terrainData.size.y, treeInstancePos.z * terrainData.size.z);
var worldPos = Terrain.activeTerrain.transform.TransformPoint(localPos);
resourcePositions.Add(worldPos);
}
On the first line we just retrieve the position on the heightmap. Then we convert it to local position and finally to world position.