- Home /
GUI.button and onClick Terrain
I'm developing a 2D "Shoot'em up" game where my main character is stationary on the left of the screen and shoots where ever I click on the screen(using raycast). I have a pause button on the bottom right and every time I click the pause button, it shoots my main characters gun. Is there anyway to avoid this happening as it looks messy and buggy.
Any help would be greatly appreciated. Thanks!
If one of these answers has resolved your concern, please vote it up and accept it. 2 Good answers here, you should at the very least, let everyone know if you have found what you were looking for.
Answer by clunk47 · Jul 24, 2013 at 05:11 PM
Well if you define your pause button Rect in start or awake, you can setup a mouse position and check if that Rect contains it. Then you can have a bool that determine whether or not you are allowed to fire your gun. Since you didn't post your code, I'll give you a basic, easy to understand example. Hope this helps :)
Rect pauseBtnRect;
Vector2 mouse;
bool canFire;
void Awake()
{
pauseBtnRect = new Rect(0, 0, 128, 64);
}
void Update()
{
mouse = new Vector2(Input.mousePosition.x, Screen.height - Input.mousePosition.y);
if(pauseBtnRect.Contains(mouse))
canFire = false;
else
canFire = true;
if(canFire)
{
if(Input.GetButton("Fire1"))
//Your firing code
}
}
void OnGUI()
{
if(GUI.Button(pauseBtnRect, "Pause"))
//Your pause code.
}
Answer by chris_taylor · Jul 24, 2013 at 05:05 PM
When You test for the input for shooting the gun add a test to make sure the mouse is not within the Rect of the button. The answer on this question tells you how you can do this.
But isn't the GUI.button in its own "layer" ontop of the scene. The x,y cords are screen resolution and not the 3D plane x,y cords so how would I check if my click is in that rect?
your pause button is in 3d space? If so you could raycast from the mouse pos and check if the ray intersects the bounds of the button
http://docs.unity3d.com/Documentation/ScriptReference/Bounds.IntersectRay.html
If your button is not GUI, and is in 3D space, just use a raycast like you're doing. Tag the button "PauseButton" for example. Then in your if(Physics.Raycast(ray, out hit)) statement, as if(hit.collider.tag == "PauseButton") and use that bool I talk about in my answer (canFire).
Ray ray;
RaycastHit hit;
bool canFire;
void Update()
{
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray, out hit))
{
if(hit.collider.tag == "PauseButton")
canFire = false;
else
canFire = true;
}
}
But if you're doing a "2D" shoot 'em up, why don't you just use Unity's simple GUI?
I am using GUI.Button with a GUIS$$anonymous$$IN to texture/style it.
Our answers aren't quite the same. Yours is a reference to another question. He already knows how to use a button. He needs a condition in which he can or cannot fire.