- Home /
Avoid touch input when pressing the "Pause" button
The player moves whenever I touch the screen in my game. The issue is that when I press the "Pause" button, the player moves for as long as I hold down the button before releasing.
How can I make the touch input only count for a certain range of the screen? I have read about raycast but I've got no clue how to implement it in my game.
 void Update() {
       if (Input.GetMouseButton(0) && Time.timeScale != 0) {
          rb.velocity = new Vector2(moveSpeed, moveSpeed);
          transform.rotation = Quaternion.Euler(0, 0, -42);
       } else {
          rb.velocity = new Vector2(-moveSpeed, moveSpeed);
          transform.rotation = Quaternion.Euler(0, 0, 42);
       }
Thank you in advance!
Answer by bhavinbhai2707 · Dec 25, 2019 at 06:41 PM
There are 2 simple ways of doing it.
- Set - Time.timeScale = 0;when you press the pause button. Doing that will freeze the game completely and no matter how much input you take the player won't move. Set- Time.timeScale = 1to unpause the game.
- If you don't want the game to be freeze and just want player to stop taking input. I am assuming that you are using an UI Button for pause button. if yes, then use - EventSystem.current.IsPointerOverGameObject()to check if the mouse is over an UI element.
This code should work for you.
     if (Input.GetMouseButton(0) && Time.timeScale != 0 && !EventSystem.current.IsPointerOverGameObject())
         {
             Debug.Log("Move your player!");
         }
- I already have Time.timeScale set the way it's supposed to be. 
- EventSystem.current.IsPointerOverGameObject()detects all gameObjects with boxColliders. How can I make it bypass all the other ones except the button?
@$$anonymous$$atdrox EventSystem.current.IsPointerOverGameObject() only works for UI. Do you have EventSystem in your hierarchy? 
Check this Link for unity documentation of it!
I do have an EventSystem object. I've tried using a sprite and a quad but as soon as they have a box collider they apparently count as UI elements and I need to have those in my game.
I put a 2D box collider on my player and this happens when I have my mouse over it: https://gyazo.com/95b3b9f074a46f11741bd0b2ef80c879
Your answer
 
 
             Follow this Question
Related Questions
Move horizontally on touch 0 Answers
Unity 2D Mobile Game Drawing Mechanic 0 Answers
Different animations on mobile 0 Answers
How to detect screen touching more frequently than fps. 1 Answer
Receiving UI/touch events while mobile soft keyboard is open 0 Answers
 koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                