- Home /
rts building placement
I'm building a RTS type game. So far the game allows selecting objects from a menu of icons, then once selected, lets them place the objects with the mouse cursor by left clicking. There's also a cost for each shape, once the money runs out it says out of money.
One problem im having that I must figure out is, when the icons are clicked, it spawns the object at the same time. Here is my code.
var cash : int = 2000;
var boxIcon : Texture2D;
var sphereIcon : Texture2D;
var cylinderIcon : Texture2D;
var cubeCost : int = 400;
var sphereCost : int = 200;
var cylinderCost : int = 600;
private var building;
private var buildingCost : int = 0;
function OnGUI ()
{
if (GUI.Button (Rect (10,10, 50, 50), GUIContent( boxIcon, "Build a box") ))
{
building = GameObject.Find("Cube");
buildingCost = cubeCost;
}
if(GUI.Button (Rect (60,10,50,50), GUIContent( sphereIcon, "Build a sphere") ))
{
building = GameObject.Find("Sphere");
buildingCost = sphereCost;
}
if(GUI.Button(Rect ( 110,10,50,50), GUIContent( cylinderIcon, "Build a cylinder") ))
{
building = GameObject.Find("Cylinder");
buildingCost = cylinderCost;
}
}
function Update () {
if(Input.GetMouseButtonDown(0))
{
var hit : RaycastHit;
var ray : Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray,hit,300)&&building && cash >= buildingCost)
{
Instantiate(building,hit.point,Quaternion.identity);
switch(building)
{
case GameObject.Find("Sphere"):
cash -= 200;
break;
case GameObject.Find("Cube"):
cash -= 400;
break;
case GameObject.Find("Cylinder"):
cash -= 600;
break;
default: print ("nothings the case!");
break;
}
}
else
{
print("not enough money");
}
}
}
Answer by Berenger · Feb 12, 2012 at 04:25 AM
When you click on a button, Input.GetMouseButtonDown(0) still become true. To fix that, you need to know when you're above the gui. you can either use tooltips (if(GUI.tooltip == "button" ) etc) but be careful, you might have some surprise during the clic, tooltip doesn't seem reliable in those situations. The other is with Rect.Contains.
Hello.
Could you explain a bit further please? Perhaps change my existing code in order to show what you mean.
var isHoverGUI : bool = false; var rect : Rect = Rect (10,10, 150, 50);
function OnGUI(){
// Your stuff here ...
isHoverGUI = rect.Contains( Event.current.mousePosition );
}
function Update(){
if(Input.Get$$anonymous$$ouseButtonDown(0) && !isHoverGUI ){
//...
}
}
the method worked. Thanks! I will have to study how it worked for a while.