Friday, March 7, 2014

Handling Multi Touch in Unity 3D

While working on my Unity Project, I faced some strange problem. I had few buttons on screen and I was handling touch by handling Mouse Event. While it worked fine if you use it with mouse, but when I try same on phone with Touch, I realized that my button can not detect touch if I already touched some other button. So basically in case of multi touch, mouse events do not work. This introduced problem if user is touching button very rapiddly, so to resolve issue, we need to handle multi touch.

Handling multi touch is simple in Unity. You can put the following code in Update method and you will be ready to handle multi touch.

  
  // Check if there is any touch event 
  if (Input.touchCount > 0)
  { 
   //get last touch and its location on screen
   Touch touch = Input.GetTouch(Input.touchCount-1);
   Vector3 wp = Camera.main.ScreenToWorldPoint(touch.position);

   //check if that location collides with our collider
   if (collider2D == Physics2D.OverlapPoint(wp)){    
    if(touch.phase == TouchPhase.Began){
    // Touch just began
    }else if(touch.phase == TouchPhase.Canceled 
              || touch.phase == TouchPhase.Ended ) {
    //Touch canceled or ended
    }
   }
  }
That's it. Thanks for visiting my blog.

1 comment: