As I promised there is a super easy tutorial for beginners (and who were afraid about it just like me 🙂 ) about touch input with Unity

First of all, there are a few things you need to know. Unity using 3 different coordinate spaces:

  • Word Space: this is what you can see in Unity editor (transfor.position)
  • Screen Space: it uses pixels as the basic unit. The bottom left of the screen is always (0,0) and the top right is always (screen width in pixels, screen height in pixels)
  • Viewport Space: This is screen space but normalized, so the bottom left corner is (0,0) and the top right is (1,1)

So for example if you’ll use Touch.position then as you can see in the documentation that it returns with pixels. you can use that data OR you can convert it to Word space, Viewport Space. This is pretty easy with Unity:

Here you can see an example C# code what detects if the left or the right half of the screen was touched:

void Update () {
		
		#if UNITY_EDITOR || UNITY_STANDALONE || UNITY_WEBPLAYER
		
		horizontalInput = (int)(Input.GetAxisRaw("Horizontal"));
		verticalInput = (int)(Input.GetAxisRaw("Vertical"));
		
		#elif UNITY_ANDROID || UNITY_IOS || UNITY_IPHONE || UNITY_WP8

		//Check if Input has registered more than zero touches
		if(Input.touchCount > 0){
			//Store the first touch detected.
			Touch myTouch = Input.touches[0];
			//Check if the phase of that touch equals Began (so you just put down your finger)
			if (myTouch.phase == TouchPhase.Began)
			{
				//If so, set touchOrigin to the position of that touch (returns with pixels)
				touchOrigin = myTouch.position;
				//We need to convert it to viewport so we can easy detect if the left or right half of the screen was touched
				Vector3 touchOriginConverted = Camera.main.ScreenToViewportPoint(touchOrigin);
				
				if(touchOriginConverted.x < 0.5){
					horizontalInput = -1;
					Debug.Log("The LEFT half was touched");
				} else if(touchOriginConverted.x > 0.5){
					horizontalInput = 1;
					Debug.Log("The RIGHT half was touched");
				}
				//When the touch is ended we don't want to move left or right anymore so that's why it's zero
			} else if(myTouch.phase == TouchPhase.Ended){
				horizontalInput = 0;
				verticalInput = 0;
				Debug.Log("The touch ended");
			}
		}
		#endif}

With this I could understand it and build more complex touch inputs. (swipe horizontal, vertical etc…)
If anything is unclear then just leave a comment below and I’ll happy to reply. 🙂

Advertisements