- Home /
Placing my GameObject on a Ground with differences in height
Hello,
my Problem is that I downloaded a low poly Asset and the Ground has differences in height (for example at x=34 and z=20, y=2 and at x=50 and z=12, y=5). Now I want to spawn random Objects on the Ground (trees, mushrooms, etc.), but my problem is the difference in height which the Ground has. The pivot of the game objects/Prefabs are at the bottom.
Thanks in advance. :)
Answer by unity_ek98vnTRplGj8Q · Feb 20, 2020 at 11:30 PM
If you are using Unity's terrain feature, calling Terrain.activeterrain.SampleHeight() will give you the height of the terrain pretty easily. If you are just using a normal mesh, make sure it has a mesh collider and you can Raycast down to get the height of the mesh at any position.
public LayerMask groundLayer;
public float DetectGroundHeight(Vector3 position){
position.y = 100; //Make sure this value is higher that your tallest bit of ground
RaycastHit hit = new RaycastHit();
Ray ray = new Ray(position, Vector3.down);
if(Physics.Raycast(ray, out hit, 1000, groundLayer)){
return hit.point;
}
//If no hit then you have attempted to measure the height somewhere off the mesh
return Mathf.NegativeInfinity;
}
Answer by tormentoarmagedoom · Feb 20, 2020 at 04:34 PM
Hello. There.
I dont know if there is any other solution. But you can create a "ground detector" object. (An empty object with trigger collider and script).
Then, at the X and Z coords where you want to spawn a tree, start moving the detector down, once it collides with the ground, you know the height.