Hey totally forgot to ever share the 8 directional version! Sorry if anybody had been waiting on that!
This version allows the mouse to emulate touches in the editor (great for debugging and rapid prototyping) and of course has 8 directions of “swipe detection” rather than only 4.
Anyway I didn’t write all of this, and instead found most of this in another topic ( Swipe in all directions Touch and Mouse - Unity Engine - Unity Discussions ), although there might be modifications here and there, it should help get you going in the right direction
SwipeManager.cs
using UnityEngine;
using System.Collections;
public struct SwipeAction
{
public SwipeDirection direction;
public Vector2 rawDirection;
public Vector2 startPosition;
public Vector2 endPosition;
public float startTime;
public float endTime;
public float duration;
public bool longPress;
public float distance;
public float longestDistance;
public override string ToString()
{
return string.Format(“[SwipeAction: {0}, From {1}, To {2}, Delta {3}, Time {4:0.00}s]”, direction, rawDirection, startPosition, endPosition, duration);
}
}
public enum SwipeDirection
{
None, // Basically means an invalid swipe
Up,
UpRight,
Right,
DownRight,
Down,
DownLeft,
Left,
UpLeft
}
///
/// Swipe manager.
/// BASED ON: Swipe in all directions Touch and Mouse - Unity Engine - Unity Discussions
///
public class SwipeManager : MonoBehaviour
{
public System.Action onSwipe;
public System.Action onLongPress;
[Range(0f, 200f)]
public float minSwipeLength = 100f;
public float longPressDuration = 0.5f;
Vector2 currentSwipe;
SwipeAction currentSwipeAction = new SwipeAction();
void Update()
{
DetectSwipe();
}
public void DetectSwipe()
{
var touches = InputHelper.GetTouches();
if (touches.Count > 0)
{
Touch t = touches[0];
if (t.phase == TouchPhase.Began)
{
ResetCurrentSwipeAction(t);
}
if (t.phase == TouchPhase.Moved || t.phase == TouchPhase.Stationary)
{
UpdateCurrentSwipeAction(t);
if (!currentSwipeAction.longPress && currentSwipeAction.duration > longPressDuration && currentSwipeAction.longestDistance < minSwipeLength)
{
currentSwipeAction.direction = SwipeDirection.None; // Invalidate current swipe action
currentSwipeAction.longPress = true;
if (onLongPress != null)
{
onLongPress(currentSwipeAction); // Fire event
}
return;
}
}
if (t.phase == TouchPhase.Ended)
{
UpdateCurrentSwipeAction(t);
// Make sure it was a legit swipe, not a tap, or long press
if (currentSwipeAction.distance < minSwipeLength || currentSwipeAction.longPress) // Didnt swipe enough or this is a long press
{
currentSwipeAction.direction = SwipeDirection.None; // Invalidate current swipe action
return;
}
if (onSwipe != null)
{
onSwipe(currentSwipeAction); // Fire event
}
}
}
}
void ResetCurrentSwipeAction(Touch t)
{
currentSwipeAction.duration = 0f;
currentSwipeAction.distance = 0f;
currentSwipeAction.longestDistance = 0f;
currentSwipeAction.longPress = false;
currentSwipeAction.startPosition = new Vector2(t.position.x, t.position.y);
currentSwipeAction.startTime = Time.time;
currentSwipeAction.endPosition = currentSwipeAction.startPosition;
currentSwipeAction.endTime = currentSwipeAction.startTime;
}
void UpdateCurrentSwipeAction(Touch t)
{
currentSwipeAction.endPosition = new Vector2(t.position.x, t.position.y);
currentSwipeAction.endTime = Time.time;
currentSwipeAction.duration = currentSwipeAction.endTime - currentSwipeAction.startTime;
currentSwipe = currentSwipeAction.endPosition - currentSwipeAction.startPosition;
currentSwipeAction.rawDirection = currentSwipe;
currentSwipeAction.direction = GetSwipeDirection(currentSwipe);
currentSwipeAction.distance = Vector2.Distance(currentSwipeAction.startPosition, currentSwipeAction.endPosition);
if (currentSwipeAction.distance > currentSwipeAction.longestDistance) // If new distance is longer than previously longest
{
currentSwipeAction.longestDistance = currentSwipeAction.distance; // Update longest distance
}
}
SwipeDirection GetSwipeDirection(Vector2 direction)
{
var angle = Vector2.Angle(Vector2.up, direction.normalized); // Degrees
var swipeDirection = SwipeDirection.None;
if (direction.x > 0) // Right
{
if (angle < 22.5f) // 0.0 - 22.5
{
swipeDirection = SwipeDirection.Up;
}
else if (angle < 67.5f) // 22.5 - 67.5
{
swipeDirection = SwipeDirection.UpRight;
}
else if (angle < 112.5f) // 67.5 - 112.5
{
swipeDirection = SwipeDirection.Right;
}
else if (angle < 157.5f) // 112.5 - 157.5
{
swipeDirection = SwipeDirection.DownRight;
}
else if (angle < 180.0f) // 157.5 - 180.0
{
swipeDirection = SwipeDirection.Down;
}
}
else // Left
{
if (angle < 22.5f) // 0.0 - 22.5
{
swipeDirection = SwipeDirection.Up;
}
else if (angle < 67.5f) // 22.5 - 67.5
{
swipeDirection = SwipeDirection.UpLeft;
}
else if (angle < 112.5f) // 67.5 - 112.5
{
swipeDirection = SwipeDirection.Left;
}
else if (angle < 157.5f) // 112.5 - 157.5
{
swipeDirection = SwipeDirection.DownLeft;
}
else if (angle < 180.0f) // 157.5 - 180.0
{
swipeDirection = SwipeDirection.Down;
}
}
return swipeDirection;
}
}
InputHelper.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
///
/// Input helper.
/// SOURCE: http://answers.unity3d.com/answers/956579/view.html
///
public static class InputHelper
{
private static TouchCreator lastFakeTouch;
public static List GetTouches()
{
List touches = new List();
touches.AddRange(Input.touches);
// Uncomment if you want it only to allow mouse swipes in the Unity Editor
//#if UNITY_EDITOR
if (lastFakeTouch == null)
{
lastFakeTouch = new TouchCreator();
}
if (Input.GetMouseButtonDown(0))
{
lastFakeTouch.phase = TouchPhase.Began;
lastFakeTouch.deltaPosition = new Vector2(0, 0);
lastFakeTouch.position = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
lastFakeTouch.fingerId = 0;
}
else if (Input.GetMouseButtonUp(0))
{
lastFakeTouch.phase = TouchPhase.Ended;
Vector2 newPosition = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
lastFakeTouch.deltaPosition = newPosition - lastFakeTouch.position;
lastFakeTouch.position = newPosition;
lastFakeTouch.fingerId = 0;
}
else if (Input.GetMouseButton(0))
{
lastFakeTouch.phase = TouchPhase.Moved;
Vector2 newPosition = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
lastFakeTouch.deltaPosition = newPosition - lastFakeTouch.position;
lastFakeTouch.position = newPosition;
lastFakeTouch.fingerId = 0;
}
else
{
lastFakeTouch = null;
}
if (lastFakeTouch != null)
{
touches.Add(lastFakeTouch.Create());
}
// Uncomment if you want it only to allow mouse swipes in the Unity Editor
//#endif
return touches;
}
}
TouchCreator.cs
using UnityEngine;
using System.Reflection;
using System.Collections.Generic;
///
/// Touch creator.
/// BASED ON: http://answers.unity3d.com/answers/801637/view.html
///
public class TouchCreator
{
static BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
static Dictionary<string, FieldInfo> fields;
object touch;
public float deltaTime { get { return ((Touch)touch).deltaTime; } set { fields[“m_TimeDelta”].SetValue(touch, value); } }
public int tapCount { get { return ((Touch)touch).tapCount; } set { fields[“m_TapCount”].SetValue(touch, value); } }
public TouchPhase phase { get { return ((Touch)touch).phase; } set { fields[“m_Phase”].SetValue(touch, value); } }
public Vector2 deltaPosition { get { return ((Touch)touch).deltaPosition; } set { fields[“m_PositionDelta”].SetValue(touch, value); } }
public int fingerId { get { return ((Touch)touch).fingerId; } set { fields[“m_FingerId”].SetValue(touch, value); } }
public Vector2 position { get { return ((Touch)touch).position; } set { fields[“m_Position”].SetValue(touch, value); } }
public Vector2 rawPosition { get { return ((Touch)touch).rawPosition; } set { fields[“m_RawPosition”].SetValue(touch, value); } }
public Touch Create()
{
return (Touch)touch;
}
public TouchCreator()
{
touch = new Touch();
}
static TouchCreator()
{
fields = new Dictionary<string, FieldInfo>();
foreach (var f in typeof(Touch).GetFields(flags))
{
fields.Add(f.Name, f);
//Debug.Log("name: " + f.Name); // Use this to find the names of hidden private fields
}
}
}
InputController.cs - ATTACH TO A GAMEOBJECT! MODIFY TO MEET YOUR NEEDS!
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[RequireComponent(typeof(SwipeManager))]
public class InputController : MonoBehaviour
{
public Player OurPlayer; // Perhaps your playerscript?
void Start()
{
SwipeManager swipeManager = GetComponent();
swipeManager.onSwipe += HandleSwipe;
swipeManager.onLongPress += HandleLongPress;
}
void HandleSwipe(SwipeAction swipeAction)
{
//Debug.LogFormat(“HandleSwipe: {0}”, swipeAction);
if(swipeAction.direction == SwipeDirection.Up || swipeAction.direction == SwipeDirection.UpRight)
{
// move up
if(OurPlayer != null)
OurPlayer.MovePlayerUp();
}
else if (swipeAction.direction == SwipeDirection.Right || swipeAction.direction == SwipeDirection.DownRight)
{
// move right
if (OurPlayer != null)
OurPlayer.MovePlayerRight();
}
else if (swipeAction.direction == SwipeDirection.Down || swipeAction.direction == SwipeDirection.DownLeft)
{
// move down
if (OurPlayer != null)
OurPlayer.MovePlayerDown();
}
else if (swipeAction.direction == SwipeDirection.Left || swipeAction.direction == SwipeDirection.UpLeft)
{
// move left
if (OurPlayer != null)
OurPlayer.MovePlayerLeft();
}
}
void HandleLongPress(SwipeAction swipeAction)
{
//Debug.LogFormat(“HandleLongPress: {0}”, swipeAction);
}
}