Multiple Touch InputsHow To Store and Manage Multiple Touches in Unity

In this tutorial I explain how to store multiple touches within a custom list to then spawn objects that follow the movement of each touch. 

In this video, we cover:

  • 0:30 - Setting Up A Custom List Script
  • 1:25 - Creating a Script to Detect Multiple Touches
  • 2:20 - Creating a While Loop to cycle between touches
  • 2:55 - The three different touch phases we will be using
  • 3:30 - Detecting Touch Start, End and Move
  • 4:10 - Testing our touches on a mobile device
  • 4:50 - Creating a function to spawn our circle prefabs
  • 6:15 - Adding our touches to our list
  • 6:45 - Searching our list and removing our touch after it ends
  • 8:08 - Moving our circle when the touch is moved

 

Resources

  1. Orthographic Pan & Zoom Tutorial
  2. Perspective Panning Tutorial
  3. Unity Developer Remote App

 

Source Code for touchLocation.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class touchLocation {
    public int touchId;
    public GameObject circle;

    public touchLocation(int newTouchId, GameObject newCircle){
        touchId = newTouchId;
        circle = newCircle;
    }	
}

 

Source Code for multipleTouch.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class multipleTouch : MonoBehaviour {
    public GameObject circle;
    public List touches = new List();

	// Update is called once per frame
	void Update () {
        int i = 0;
        while(i < Input.touchCount){
            Touch t = Input.GetTouch(i);
            if(t.phase == TouchPhase.Began){
                Debug.Log("touch began");
                touches.Add(new touchLocation(t.fingerId, createCircle(t)));
            }else if(t.phase == TouchPhase.Ended){
                Debug.Log("touch ended");
                touchLocation thisTouch = touches.Find(touchLocation => touchLocation.touchId == t.fingerId);
                Destroy(thisTouch.circle);
                touches.RemoveAt(touches.IndexOf(thisTouch));
            }else if(t.phase == TouchPhase.Moved){
                Debug.Log("touch is moving");
                touchLocation thisTouch = touches.Find(touchLocation => touchLocation.touchId == t.fingerId);
                thisTouch.circle.transform.position = getTouchPosition(t.position);
            }
            ++i;
        }
	}
    Vector2 getTouchPosition(Vector2 touchPosition){
        return GetComponent<Camera>().ScreenToWorldPoint(new Vector3(touchPosition.x, touchPosition.y, transform.position.z));
    }
    GameObject createCircle(Touch t){
        GameObject c = Instantiate(circle) as GameObject;
        c.name = "Touch" + t.fingerId;
        c.transform.position = getTouchPosition(t.position);
        return c;
    }
}

LINK TO THIS POST

SHARE THIS POST


DISCUSSION