Last active
June 11, 2023 10:17
-
-
Save fallenblood7080/5b633630d3977fded47cc9636164f2b7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Need New Input System to Work | |
using System; | |
using UnityEngine; | |
using UnityEngine.InputSystem.EnhancedTouch; | |
using Touch = UnityEngine.InputSystem.EnhancedTouch.Touch; | |
public class SwipeManager : MonoBehaviour | |
{ | |
private Vector2 _startTouchPosition, _currentTouchPosition; | |
[SerializeField] private float _swipeThreshold = 10f; | |
public Action OnSwipeUp { get; set; } | |
public Action OnSwipeDown { get; set;} | |
public Action OnSwipeLeft { get; set;} | |
public Action OnSwipeRight { get; set;} | |
private void OnEnable() | |
{ | |
EnhancedTouchSupport.Enable(); | |
Touch.onFingerDown += ReadStartTouchPosition; | |
Touch.onFingerMove += ReadCurrentTouchPosition; | |
Touch.onFingerUp += CalculateSwipeDirection; | |
} | |
private void OnDisable() | |
{ | |
Touch.onFingerDown -= ReadStartTouchPosition; | |
Touch.onFingerMove -= ReadCurrentTouchPosition; | |
Touch.onFingerUp -= CalculateSwipeDirection; | |
EnhancedTouchSupport.Disable(); | |
} | |
private void ReadStartTouchPosition(Finger finger) | |
{ | |
_startTouchPosition = finger.currentTouch.startScreenPosition; | |
} | |
private void ReadCurrentTouchPosition(Finger finger) | |
{ | |
_currentTouchPosition = finger.currentTouch.screenPosition; | |
} | |
private void CalculateSwipeDirection(Finger finger) | |
{ | |
Vector2 dir = (_currentTouchPosition - _startTouchPosition); | |
if(dir.sqrMagnitude >= (_swipeThreshold * _swipeThreshold) * 100) | |
{ | |
if (Mathf.Abs(dir.x) > Mathf.Abs(dir.y)) | |
{ | |
//user swipe horizontal | |
if (dir.x > 0) | |
{ | |
//right | |
Debug.Log("Right!"); | |
OnSwipeRight?.Invoke(); | |
} | |
else | |
{ | |
//left | |
Debug.Log("Left"); | |
OnSwipeLeft?.Invoke(); | |
} | |
} | |
else | |
{ | |
//user swipe vertical | |
if (dir.y > 0) | |
{ | |
//up | |
Debug.Log("Up"); | |
OnSwipeUp?.Invoke(); | |
} | |
else | |
{ | |
//down | |
Debug.Log("Down"); | |
OnSwipeDown?.Invoke(); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment