/// <summary> /// Spawn a building on the position /// </summary> private void SpawnBuilding(Vector3 position, GameObject prefab, BuildingSite building) { var road = building.ParentRoad; //Make the building face the road, make a perpendicular line from the building pos to the road var lookAtPos = road.FindPerpendicularPointOnLine(new Point(position.x, position.z)).ToVector3(); //get correct spawn height from the terrain position.y = _terrain.SampleHeight(position); lookAtPos.y = position.y; //Get bounds of the prefab and store them var size = prefab.GetPrefabBounds(); building.Width = (int)size.x; building.Height = (int)size.z; //don't spawn when there is a collision var colliderPos = position; colliderPos.y += size.y / 2; if (isOverlapping(prefab, position)) { return; } //instantiate the building var go = (GameObject)Object.Instantiate(prefab, position, prefab.transform.rotation); //look at the road go.transform.LookAt(lookAtPos); //flip on Y go.transform.RotateAround(position, go.transform.up, 180); go.isStatic = true; go.SetParent(_buildingParent); building.UserData = go; //Remove grass and other details around the object //RemoveDetailsAroundGameObject((GameObject)go); //Add to the buildings list _buildings.Add(building); }
/// Check if there is an overlap private bool isOverlapping(GameObject prefab, Vector3 pos) { var colliderPos = pos; var size = prefab.GetPrefabBounds(); colliderPos.y += size.y / 2; var collisions = Physics.OverlapBox(pos, size/1.5f); return collisions.Length > 1; }