Well, title is basically the whole question itself…
You know in RTS, when you click on building button that you wish to build, for example ‘Barracks’, and then you get like semi-transparent version of that building which also follows your mouse position and shows how it would look like if you were to place it? And then as soon as you click, that half-transparent version is gone, and an actually object (or ‘barrack’ in this case) is safe and sound on the ground? =)
Well, that’s what I’m doing currently, and I’ve been trying to use instantiate with Input.mousePosition as a target position, but it won’t cut it… I just spawn a thousands of objects on the ground as I sweep my mouse across the ground…
if (hit.transform.tag == "Terrain")
{
Debug.Log("Terrain");
Instantiate(buildingTypes[0],hit.point,Quaternion.Euler(270, 75, 0));
}
Oh and if anyone’s wondering, “buildingTypes[0]” is the object I wish to build, and “Quaternion.Euler(270, 75, 0)” is used to rotate that object just right… =)
There’s a lot of steps involved to get that kind of behavior right, and I’m not going to try to go over them all. I can help you get past this particular hurdle however.
Create an invisible game object to serve as a marker for your mouse position and have it update it’s position each frame to match the world space point of your mouse cursor. Then when the player selects which building type they want to build, instantiate your ghost version of the building once, then parent it to the game object . ( ghostbuilding.transform.parent = mousemarker.transform ) The ghost building will now move around to match the mouse position. Once the player selects the position they want the building (and you check to see if the position is valid, which you’re going to have to work out on your own) destroy the ghost building and instantiate the real building at the selected position.
You just spawn 1 building with Instantiate(), and save it in a variable. So, in the next Update(), you just update the position of that building instead of spawning a new one.