Single-Double tap

doubletap

The following allows to use single and double tap for standalone and mobile.

The macros discard the useless based on platform.

public class InputController : MonoBehaviour
{
    public event Action OnSingleTap;
    public event Action OnDoubleTap;
    [Tooltip("Defines the maximum time between two taps to make it double tap")]
    [SerializeField]private float tapThreshold = 0.25f;
    private float tapTimer = 0.0f;
    private bool tap = false;

    private void Update()
    {
       UpdateInput();
    }
    private void OnDestroy()
    {
        OnSingleTap = null;
        OnDoubleTap = null;
    }

    private void UpdateInput()
    {
#if UNITY_EDITOR || UNITY_STANDALONE
        if (Input.GetMouseButtonDown(0))
        {
            if (Time.time < this.tapTimer + this.tapThreshold)
            {
                if(OnDoubleTap != null){ OnDoubleTap(); }
                this.tap = false;
                return;
            }
            this.tap = true;
            this.tapTimer = Time.time;
        }
        if (this.tap == true && Time.time > this.tapTimer + this.tapThreshold)
        {
             this.tap = false;
             if(OnSingleTap != null){ OnSingleTap();}
	}
#elif UNITY_IOS || UNITY_ANDROID
        for(int i = 0; i < Input.touchCount; i++)
        {
            if (Input.GetTouch(i).phase == TouchPhase.Began)
            {
                if(Input.GetTouch(i).tapCount == 2)
                {
                    if(OnDoubleTap != null){ OnDoubleTap();}
                }
                if(Input.GetTouch(i).tapCount == 1)
                {
                    if(OnSingleTap != null) { OnSingleTap(); }
                }
            }
        }
#endif
    }
}

If you need to pass more information like the position of the touch, then you need to update the event parameter.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s