place building like rts

hi,
I’m trying to create a small rts where you can place buildings.
I made this script but the buildings are not attached to the terrain.
how can I do to ensure that buildings can be built only on the terrain?
I would also like that the buildings are not overlapped…

var Icon1 : Texture2D;
var Icon2 : Texture2D;
var Icon3 : Texture2D;
var Edificio1:GameObject ;
var Edificio2:GameObject ;
var Edificio3:GameObject ;
var building;

var isHoverGUI : boolean = false; 
var rect : Rect = Rect (50,200, 10, 400);

function OnGUI () 
{    
    if (GUI.Button (Rect (50,200, 100,100), GUIContent( Icon1, "") ))
        building = Edificio1;        

   if(GUI.Button (Rect (50,320, 100,100), GUIContent( Icon2, "") ))
        building = Edificio2;

    if(GUI.Button(Rect ( 50,440, 100,100), GUIContent( Icon3, "") ))
        building = Edificio3;
    
    isHoverGUI = rect.Contains( Event.current.mousePosition );        
}

function Update () 
{
    if(Input.GetMouseButtonDown(0) && !isHoverGUI )
    {
        var hit : RaycastHit;
        var ray : Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        var mousePos = Input.mousePosition;
        var objectPos = Camera.main.ScreenToWorldPoint(mousePos);

        Instantiate(building,objectPos,Quaternion.identity);
    }
}

You need to use Physics.Raycast with your ray var and the terrain’s layer.

About the overlapping, that’s a bit more complicated. The quickest / dirtiest way would be to use Physics.OverlapSphere, but I guess you buildings aren’t sphericals. You should keep tracks of all the units created on a grid, where each square is free or occupied, then you can check it before building.

I would think: test the type of object your ray hit (use another API, the one that uses ‘RaycastHit’), and if it’s terrain, then you can build there. If you want all corners in the ground, you need to know the world-bounds of your house, and cast 4 rays down around the hit (assuming 4-corner house), find the one with lowest ‘Y’ value, and set the house there. As far as not overlapping, you’ll need to check the bounds of all the other houses to make sure they would not interfere with your new house, and give user some feedback as to this condition.

Just create a tag for buildings and do if (hit.tag == “tag”) That should help with your ooverlapping check not sure about your other question you seem to have 2 and I don’t use unity terrains :slight_smile: