Skip to content

Instantly share code, notes, and snippets.

@ginxx009
Created January 8, 2018 07:32
Show Gist options
  • Save ginxx009/29b491b6a678f97c843d36347b919727 to your computer and use it in GitHub Desktop.
Save ginxx009/29b491b6a678f97c843d36347b919727 to your computer and use it in GitHub Desktop.
Swipe in all directions Touch and Mouse
//inside class
Vector2 firstPressPos;
Vector2 secondPressPos;
Vector2 currentSwipe;
public void Swipe()
{
if(Input.GetMouseButtonDown(0))
{
//save began touch 2d point
firstPressPos = new Vector2(Input.mousePosition.x,Input.mousePosition.y);
}
if(Input.GetMouseButtonUp(0))
{
//save ended touch 2d point
secondPressPos = new Vector2(Input.mousePosition.x,Input.mousePosition.y);
//create vector from the two points
currentSwipe = new Vector2(secondPressPos.x - firstPressPos.x, secondPressPos.y - firstPressPos.y);
//normalize the 2d vector
currentSwipe.Normalize();
//swipe upwards
if(currentSwipe.y > 0 currentSwipe.x > -0.5f currentSwipe.x < 0.5f)
{
Debug.Log("up swipe");
}
//swipe down
if(currentSwipe.y < 0 currentSwipe.x > -0.5f currentSwipe.x < 0.5f)
{
Debug.Log("down swipe");
}
//swipe left
if(currentSwipe.x < 0 currentSwipe.y > -0.5f currentSwipe.y < 0.5f)
{
Debug.Log("left swipe");
}
//swipe right
if(currentSwipe.x > 0 currentSwipe.y > -0.5f currentSwipe.y < 0.5f)
{
Debug.Log("right swipe");
}
}
}
//inside class
Vector2 firstPressPos;
Vector2 secondPressPos;
Vector2 currentSwipe;
public void Swipe()
{
if(Input.touches.Length > 0)
{
Touch t = Input.GetTouch(0);
if(t.phase == TouchPhase.Began)
{
//save began touch 2d point
firstPressPos = new Vector2(t.position.x,t.position.y);
}
if(t.phase == TouchPhase.Ended)
{
//save ended touch 2d point
secondPressPos = new Vector2(t.position.x,t.position.y);
//create vector from the two points
currentSwipe = new Vector3(secondPressPos.x - firstPressPos.x, secondPressPos.y - firstPressPos.y);
//normalize the 2d vector
currentSwipe.Normalize();
//swipe upwards
if(currentSwipe.y > 0 currentSwipe.x > -0.5f currentSwipe.x < 0.5f)
{
Debug.Log("up swipe");
}
//swipe down
if(currentSwipe.y < 0 currentSwipe.x > -0.5f currentSwipe.x < 0.5f)
{
Debug.Log("down swipe");
}
//swipe left
if(currentSwipe.x < 0 currentSwipe.y > -0.5f currentSwipe.y < 0.5f)
{
Debug.Log("left swipe");
}
//swipe right
if(currentSwipe.x > 0 currentSwipe.y > -0.5f currentSwipe.y < 0.5f)
{
Debug.Log("right swipe");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment