Skip to content

Instantly share code, notes, and snippets.

@m039
Last active Jan 25, 2017
Embed
What would you like to do?
Very easy implementation to handle basic horizontal and vertical swipes for Unity on mobile devices
/// <summary>
/// TouchController allows you to handle basic swipes (left, right, top, bottom) on mobile device.
///
/// Usage: extend this class and don't forget to call Update in MonoBehaviour.Update
/// <summary>
public abstract class TouchController {
private readonly float _swipeThreshold;
private Vector2 _firstPosition;
private Vector2 _lastPosition;
protected TouchController(float thresholdInUnits) {
_swipeThreshold = thresholdInUnits * Screen.dpi;
_firstPosition = _lastPosition = Vector2.zero;
}
/// <summary>
/// Call this function in MonoBehaviour.Update
/// </summary>
public void Update() {
if (Input.touchCount > 0) {
var touch = Input.GetTouch(0);
switch (touch.phase) {
case TouchPhase.Began:
_firstPosition = _lastPosition = touch.position;
break;
case TouchPhase.Moved:
_lastPosition = touch.position;
break;
case TouchPhase.Ended:
if (Vector2.Distance(_firstPosition, _lastPosition) > _swipeThreshold) {
if (Mathf.Abs(_firstPosition.x - _lastPosition.x) >
Mathf.Abs(_firstPosition.y - _lastPosition.y)) {
if ((_lastPosition.x > _firstPosition.x)) {
OnSwipe(MoveDirection.Left);
} else {
OnSwipe(MoveDirection.Right);
}
} else {
if (_lastPosition.y > _firstPosition.y) {
OnSwipe(MoveDirection.Down);
} else {
OnSwipe(MoveDirection.Up);
}
}
}
break;
case TouchPhase.Canceled:
_firstPosition = _lastPosition = Vector2.zero;
break;
}
}
}
protected abstract void OnSwipe(MoveDirection direction);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment