Question by
NeonStranger · Sep 29, 2021 at 12:28 PM ·
scripting problemscript.scripting beginnerscriptingbasics
Swipe Detection Script not working as intended
I have this script for detection of swipes, but whenever I swipe, the output is either 2, 3, or 4 swipes. I only want the swipe to be detected once, so this is not optimal for me.
using System;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class SwipeDetector : MonoBehaviour
{
private Vector2 fingerDown;
private Vector2 fingerUp;
public bool detectSwipeOnlyAfterRelease = false;
public UnityEvent OnUpSwipe;
public UnityEvent OnDownSwipe;
public UnityEvent OnLeftSwipe;
public UnityEvent OnRightSwipe;
public float SWIPE_THRESHOLD = 20f;
private bool isJumping = true;
// Update is called once per frame
void Update()
{
foreach (Touch touch in Input.touches)
{
if (touch.phase == TouchPhase.Began)
{
fingerUp = touch.position;
fingerDown = touch.position;
}
//Detects Swipe while finger is still moving
if (touch.phase == TouchPhase.Moved)
{
if (!detectSwipeOnlyAfterRelease)
{
fingerDown = touch.position;
checkSwipe();
}
}
//Detects swipe after finger is released
if (touch.phase == TouchPhase.Ended)
{
fingerDown = touch.position;
checkSwipe();
}
}
}
void checkSwipe()
{
//Check if Vertical swipe
if (verticalMove() > SWIPE_THRESHOLD && verticalMove() > horizontalValMove())
{
//Debug.Log("Vertical");
if (fingerDown.y - fingerUp.y > 0)//up swipe
{
OnSwipeUp();
}
else if (fingerDown.y - fingerUp.y < 0)//Down swipe
{
OnSwipeDown();
}
fingerUp = fingerDown;
}
//Check if Horizontal swipe
else if (horizontalValMove() > SWIPE_THRESHOLD && horizontalValMove() > verticalMove())
{
//Debug.Log("Horizontal");
if (fingerDown.x - fingerUp.x > 0)//Right swipe
{
OnSwipeRight();
}
else if (fingerDown.x - fingerUp.x < 0)//Left swipe
{
OnSwipeLeft();
}
fingerUp = fingerDown;
}
//No Movement at-all
else
{
//Debug.Log("No Swipe!");
}
}
float verticalMove()
{
return Mathf.Abs(fingerDown.y - fingerUp.y);
}
float horizontalValMove()
{
return Mathf.Abs(fingerDown.x - fingerUp.x);
}
//////////////////////////////////CALLBACK FUNCTIONS/////////////////////////////
void OnSwipeUp()
{
if(isJumping == false){
isJumping = true;
Debug.Log("Swipe UP");
OnUpSwipe.Invoke();
}
}
void OnSwipeDown()
{
Debug.Log("Swipe Down");
OnDownSwipe.Invoke();
}
void OnSwipeLeft()
{
Debug.Log("Swipe Left");
OnLeftSwipe.Invoke();
}
void OnSwipeRight()
{
Debug.Log("Swipe Right");
OnRightSwipe.Invoke();
}
public void OnLanding(){
isJumping = false;
}
}
Comment
Your answer
Follow this Question
Related Questions
Set public gameobject by raycast hit target 1 Answer
How do i make an uppercut attack? 0 Answers
Make enemy patrol without Nav Points? 0 Answers
UnityCar - Controlling Speed with a duration? 2 Answers
Image UI not enabling C# SOLVED 1 Answer