Making an Input Listener Via Touch

Do you know how to make touch screen functionality on specific coordinates of the screen, especially used for buttons and regardless of the screen size, density, and the phone OS itself? (e.g. iOS, Android) I want to check for its touch coordinates and the response according to that coordinate. I’m on the experimental works of my current game project. I’m using C# for programming some few behaviors according to that object.

Here is the answer:

        if(Input.touchCount == 0) {
            // Put any logics related to non-touchscreen games. (e.g. desktop)
            return; // --> Put this after the code within this condition.
		} else if(Input.touchCount == 1) {
			if(Input.GetTouch(0).phase == TouchPhase.Moved) { // --> When user touch dragged...
				// This code is optional. Uses to check for touch coordinates.
				// Take note that the coordinate always start at center of
				// the screen.
				Ray ray = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);
				transform.position = ray.GetPoint(distance);
				Debug.Log ("Touch Coordinate: (" + transform.position.x + ", " + transform.position.y + ")");
			}
		}

Here are some basic lists of the conditions to check for touch behavior and put it in the IF-ELSE condition:

  • Input.GetTouch(0).phase == TouchPhase.Moved → Checks if the touch is dragging.
  • Input.GetTouch(0).phase == TouchPhase.Began → Checks if the touch is down.
  • Input.GetTouch(0).phase == TouchPhase.Ended → Checks if the touch is lifted.

Also, if you’re using Input.touchCount, this can be used in -IF-ELSE statement and checks for the number of touches. If number of touches is zero, this will be precedeed by mouse click behavior.