- Home /
Instantiate trees on terrain with perfect height.
I want to make a survival game where the player is able to chop down trees. I want these trees to randomly be instantiated on a terrain. Problem is, that I don't know how to make them instantiate so that they adapt to the terrain's height/hills. Any ideas?
Thanks in advance!
Answer by Evaldas_Unity · May 29, 2017 at 07:50 AM
Hey Ferish, you can use Terrain.SampleHeight() to achieve this. Using the example on ScriptReference page, will get you a vector3 which is at the height of the terrain.
Hope this helps. : )
Answer by Bill9009 · May 29, 2017 at 07:07 AM
If you can get the random x and z axis you can try this. This gives you the y value to spawn the tree at.
float? SpawnTreeY(float x, float z)
{
float hoverHeight = 100;
Ray r = new Ray(new Vector3(x, hoverHeight, z), Vector3.down);
RaycastHit hit;
if (Physics.Raycast(r, out hit))
{
return hoverHeight - hit.distance;
}
else
{
return null;
}
}
Very cheeky, but nice thinking! But what if the ray hits another tree, or a rock :P
$$anonymous$$aybe test it by using "hit.transform.gameObject"
Simply use a layermask. Although I'm not really familiar with the built-in terrain so there may be complications. Then use the answer below (sampleheight).
Your answer
Follow this Question
Related Questions
Tree Instance Static Batching 0 Answers
Terrain Trees Disappear (Tree Distance is 2000) 1 Answer
Tree brush making very tiny trees 0 Answers
Trees Appearing under the Terrain 2 Answers
Making the Terrain Trees Break 1 Answer