Hi,
I’m struggeling with the implementation of the building function like in every RTS.
I’ve 2 classes, attached to my main camera that should handel the building.
1.) BuilingsManager, which simply generates the GUI based on avaiable Prefabs:
public class BuildingManager : MonoBehaviour {
public GameObject[] buildings;
private BuildingPlacement buildingPlacement;
// Use this for initialization
void Start () {
buildingPlacement = GetComponent<BuildingPlacement>();
}
// Update is called once per frame
void Update () {
}
void OnGUI()
{
for(int i = 0; i < buildings.Length; i++)
{
if(GUI.Button(new Rect(Screen.width/20, Screen.height/15+Screen.height/12*i, 200,30), buildings[i].name))
{
buildingPlacement.SetItem(buildings[i]);
}
}
}
}
And the BuildingPlacement Class, that should build the Structure on the selected point:
using UnityEngine;
using System.Collections;
public class BuildingPlacement : MonoBehaviour
{
private Transform currentBuilding;
private bool hasPlaced;
// Use this for initialization
void Start()
{
Cursor.visible = true;
}
// Update is called once per frame
void Update()
{
if (currentBuilding != null && !hasPlaced)
{
Vector3 m = Input.mousePosition;
m = new Vector3(m.x, m.y, transform.position.y);
Vector3 p = GetComponent<Camera>().ScreenToWorldPoint(m);
currentBuilding.position = new Vector3(p.x, p.y, p.z);
if (Input.GetMouseButtonDown(0))
{
hasPlaced = true;
}
}
}
public void SetItem(GameObject b)
{
hasPlaced = false;
currentBuilding = ((GameObject)Instantiate(b)).transform;
}
}
There’s also the attempt to do this via raycasting:
RaycastHit hit;
Ray ray = new Ray(transform.position, transform.forward);
if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit))
{
specificVector.Set(hit.point.x, hit.collider.transform.position.y, hit.point.z);
currentBuilding.transform.position = specificVector;
}
Which could replace the Vector3 m part
My probem here is, that once I clicked on the GUI Button, the Item is placed floating in the air in 4 out of 5 attempts. Addtionally, if it magically allows the item to follow the mouse, it’s built somewhere in the ait instead on the ground.
I’ll attach a short video, so you’ll get a better Idea of the problem:
I hope someone can help me here