Hi all, I’m having trouble with what should be a fairly simple script to detect swipe movement. The event “onSwipe” is not invoked and I am unsure why. Any help would be greatly appreciated!
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
public enum SwipeDirection
{
Left,
Right,
Up,
Down
}
public class SwipeManager : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
[System.Serializable]
public class SwipeEvent : UnityEvent<SwipeDirection> { }
[System.Serializable]
public struct Events
{
#pragma warning disable 649
[SerializeField]
private SwipeEvent _onSwipe;
public SwipeEvent onSwipe
{
get { return _onSwipe; }
}
#pragma warning restore 649
}
public float minimumSwipeDistance;
public Events events;
public void OnBeginDrag(PointerEventData eventData)
{
}
public void OnDrag(PointerEventData eventData)
{
}
public void OnEndDrag(PointerEventData eventData)
{
Vector3 dragVectorDirection = (eventData.position - eventData.pressPosition).normalized;
float distance = Vector3.Distance(eventData.pressPosition, eventData.position);
if (distance >= minimumSwipeDistance)
{
SwipeDirection direction = Direction(dragVectorDirection);
events.onSwipe.Invoke(direction);
}
}
private SwipeDirection Direction(Vector3 dragVector)
{
float positiveX = Mathf.Abs(dragVector.x);
float positiveY = Mathf.Abs(dragVector.y);
SwipeDirection draggedDir;
if (positiveX > positiveY)
{
draggedDir = (dragVector.x > 0) ? SwipeDirection.Right : SwipeDirection.Left;
}
else
{
draggedDir = (dragVector.y > 0) ? SwipeDirection.Up : SwipeDirection.Down;
}
return draggedDir;
}
}