Place a game object on terrain

I want to instantiate a prefab at a particular (x,z) position on a terrain, so that it is sitting on the terrain. At the moment I’m using (in C#):

Vector3 pos = new Vector3(x,0,z);
pos.y = terrain.SampleHeight(pos);
			
GameObject obj = Instantiate(prefab, 
                             terrain.transform.TransformPoint(pos),
                             Quaternion.identity) as GameObject;

But of course the object is embedded in the surface. How do I calculate the y-offset I need to add to make the object sit on the terrain?

Hey Malcolmr,

three ideas spring to mind:

  1. add a field to a script on the prefab for height, and add it to the y prior to spawning the new instance
  2. move the pivot point of the prefab to the actual model bottom, instead of dead centre (may have other side-effects!)
  3. use the actual mesh data to calc the height of the model, and then add half that to the y-offset

Hope this helps,

Galen

I think you could also use the collider height to compute the offset, assuming it has a collider.

I have used the following to create a random number of targets around a given distance (radius) of the first person controller:

var player : Transform;
var preFab : Transform;
var numberTargets : int;
var radius : float;

function Start()
{
var position :Vector3;
var i : int;
for(i = 0; i< numberTargets; i++)
{
position = Vector3(player.position.x + Random.Range(-radius,radius),0.0f,player.position.z + Random.Range(-radius,radius));
position.y = Terrain.activeTerrain.SampleHeight(position) + Terrain.activeTerrain.transform.position+y; //I had a student move the terrain on me necessating adding the y position of the terrain
var target = Instantiate(preFab, position, Quatenrion.identity);
target.transform.position.y = target.transform.position.y + target.transform.collider.bounds.size.y/2;
}

}

1 Like

This is a nice code but it’s not a random inside a circle, it’s a random inside a square.

In order to choose a random point inside a circular area you need a random float variable within the range of 0 to 360 representing the angle and another random float to represent the distance/the radius…
Then you can do something like sin and cos with this angle and distance and it should give you the random point in a circular area within the radius you want.
(Of course you will have to add up players position if you want the center of your circle to by your player or in other words be relative to the player…)
Hope I helped :slight_smile: