Setting a game object's y position equal to a terrain's

In a 3d game, how do I set a moving game object’s position equal to that of the terrain’s which has a changing height?

I have a terrain that has hills, I’m able to get random x & z positions easily enough and so far, I’ve just been using the gameObject’s current y position, which has been fine since I’ve been working with a flat terrain. Now, however, using this method will make the gameObject’s y position constant/static, regardless of where it it on the terrain. How do I make it be that of the current terrain where the gameObject is currently at?

You could use Physics.Raycast, and shoot a ray down from the sky from above the object, onto the terrain collider (assuming you have a collider) to get a point on the terrain

Hi there!

To do this we use a concept called “Raycasting”

    //Returns a position on your terrain
    static Vector3 GetTerrainPos(float x, float y)
    {
        //Create object to store raycast data
        RaycastHit hit;

        //Create origin for raycast that is above the terrain. I chose 100.
        Vector3 origin = new Vector3(x, 100, y);

        //Send the raycast.
        Physics.Raycast(origin, Vector3.down, out hit, Mathf.Infinity);

        Debug.Log("Terrain location found at " + hit.point);
        return hit.point;
    }

In short, this function returns a position based on the x and y variable you give it. It is a bit unclear how you want it implemented, but regardless this should help you.

Just run this function with the x and y values, and set the position using:

transform.position = GetTerrainPos(x, y); 

Let me know if you have any questions, this should get you started in the right direction though!