luii
luii

Reputation: 339

Snap a house model to the ground in unity

I have a dataset of 3d houses made up of many other models. The houses are very diverse. I am trying to find a way to snap the house to the terrain, using a script. The script kind of works, the issue is that sometimes the model is embedded within the terrain even after adjusting the pivot. How I can fix it, so that once snapped objects just sit on top of the terrain and not inside of it?

public class AlignInEditor : MonoBehaviour 
{
    public bool align = false;
    public bool showLineToSurface = false;

    void Update () 
    {
        if (align)
        {
            RaycastHit hit;
            Ray ray = new Ray (transform.position, Vector3.down);
            if (Physics.Raycast(ray, out hit))
            {
                transform.position = hit.point;
                Debug.Log (transform.name + " aligned.");
            }
            else
            {
                Debug.Log ("No surface found for " + transform.name);
            }
            align = false;
        }

        if (showLineToSurface)
        {
            RaycastHit hit;
            Ray ray = new Ray (transform.position, Vector3.down);
            if (Physics.Raycast(ray, out hit))
            {
                Debug.DrawLine (transform.position, hit.point);
            }
        }
    }
}

House embedded in terrain

Upvotes: 0

Views: 1993

Answers (1)

user8303828
user8303828

Reputation:

Cast a raycast form the center of the house to the ground to find the first point. Then cast a raycast from that point (vertically) to the house and find the second point. Then find the distance between that 2 points. Then place the house on the second point (on the ground) + the found distance.

Upvotes: 0

Related Questions