Skip to content

Instantly share code, notes, and snippets.

@AndreiPrystupchyk
Forked from Fonserbc/SwipeInput.cs
Created February 18, 2021 08:48
Show Gist options
  • Save AndreiPrystupchyk/484b65df0252b5da0c82f14e910b2751 to your computer and use it in GitHub Desktop.
Save AndreiPrystupchyk/484b65df0252b5da0c82f14e910b2751 to your computer and use it in GitHub Desktop.
A simple swipe detector for touchscreens for Unity3D. Four cardinal directions.
using UnityEngine;
public class SwipeInput : MonoBehaviour {
public const float MAX_SWIPE_TIME = 1f;
public const float MIN_SWIPE_DISTANCE = 0.17f;
public static bool swipedRight = false;
public static bool swipedLeft = false;
public static bool swipedUp = false;
public static bool swipedDown = false;
public static bool justTouch = false;
public bool debugWithArrowKeys = true;
Vector2 startPos;
float startTime;
public void Update()
{
swipedRight = false;
swipedLeft = false;
swipedUp = false;
swipedDown = false;
justTouch = false;
if (Input.touches.Length > 0)
{
Touch t = Input.GetTouch(0);
if(t.phase == TouchPhase.Began)
{
startPos = new Vector2(t.position.x/(float)Screen.width, t.position.y/(float)Screen.width);
startTime = Time.time;
}
if(t.phase == TouchPhase.Ended)
{
if (Time.time - startTime > MAX_SWIPE_TIME) // press too long
return;
Vector2 endPos = new Vector2(t.position.x/(float)Screen.width, t.position.y/(float)Screen.width);
Vector2 swipe = new Vector2(endPos.x - startPos.x, endPos.y - startPos.y);
// Too short swipe, touch
if (swipe.magnitude < MIN_SWIPE_DISTANCE)
{
justTouch = true;
return;
}
if (Mathf.Abs (swipe.x) > Mathf.Abs (swipe.y)) { // Horizontal swipe
if (swipe.x > 0) {
swipedRight = true;
}
else {
swipedLeft = true;
}
}
else { // Vertical swipe
if (swipe.y > 0) {
swipedUp = true;
}
else {
swipedDown = true;
}
}
}
}
if (debugWithArrowKeys) {
swipedDown = swipedDown || Input.GetKeyDown("down");
swipedUp = swipedUp || Input.GetKeyDown("up");
swipedRight = swipedRight || Input.GetKeyDown("right");
swipedLeft = swipedLeft || Input.GetKeyDown("left");
justTouch = justTouch || Input.GetKeyDown("space");
}
}
}
@AndreiPrystupchyk
Copy link
Author

Touch added.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment