How to differentiate touches on mobile devices


I am working on a simple 2D game that uses the mobile joystick from Unity’s Standard Assets to control the player. On top of using the virtual joystick, I want to have the player shoot a ball in the direction that the player touches.

if (Input.touchCount > 0)
      Vector3 touchPos = Camera.main.ScreenToWorldPoint(Input.touches[0].position);
      touchPos.y -= MyUtils.cameraOffset;

The problem is, when the player is using the joystick, that touch is also captured, so the player starts shooting uncontrollably.

Is there a way to “differentiate” the touch used to control the joystick?

Never rely on the index of a tough in the touches array. Every Touch gets a fingerId when it “Began” and it will stay the same until the touch is Canceled or Ended. The position inside the touches array can change. If you have 4 active touches your desired touch might be at index 3. However when the first 3 touches are gone the fourth touch (originally at index 3) will now be the only touch left at index 0.

You may also have a look at Touch-phase or Touch in general.