Last active
July 11, 2017 12:54
-
-
Save bengsfort/768b68f7b4168b714f2dc5a1cdcbc004 to your computer and use it in GitHub Desktop.
A template for basic single-touch handling in Unity.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
public class TouchController : MonoBehaviour | |
{ | |
int _activeFinger = -1; | |
void Update () | |
{ | |
ReadTouches(); | |
} | |
void ReadTouches () | |
{ | |
// Iterate through each touch | |
foreach (Touch touch in Input.touches) | |
{ | |
// If we have no active touch and one is starting, set it to active | |
if (_activeFinger < 0 && TouchPhase.Began == touch.phase) | |
{ | |
_activeFinger = touch.fingerId; | |
HandleTouch(touch); | |
return; | |
} | |
// If this is the active touch, handle it | |
if (_activeFinger == touch.fingerId) | |
{ | |
HandleTouch(touch); | |
// Reset _activeFinger is the touch is ending | |
if (TouchPhase.Canceled == touch.phase || TouchPhase.Ended == touch.phase) | |
_activeFinger = -1; | |
return; | |
} | |
} | |
} | |
void HandleTouch (Touch touch) | |
{ | |
// Do whatever you need to do with the touch | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a template class for basic single-touch detection/handling in Unity. It functions by cacheing the currently active Touch ID and discarding any other touches throughout the lifetime of the touch.
I don't use a switch statement as in this situation only one touch should be used each frame; so instead I try to filter out the two cases via normal if statements (no active touch, new touch object / active touch, correct touch object) and handle those cases accordingly.
The same principal could be used for handling multiple touches or gestures by updating it to use a Switch statement and storing finger ID's and associated touch data in a dictionary. If there is any interest I can post another gist (or update this one) to show an implementation of this as well. :)