Tutorial: Detect swipe direction simple and easy, no need to use update

Hi guys, I wrote this simple tutorial wich is basically 7 lines of code and works like a charm. Easy and simple. You just have to use te build in Unity event system instead to write long and useless code.
No need to use an update or fixed update.
Here a snipped of the code:

public void OnEndDrag(PointerEventData eventData)
{
Vector3 dragVectorDirection = (eventData.position - eventData.pressPosition).normalized;
GetDragDirection(dragVectorDirection);
}
private enum DraggedDirection
{
   Up,
   Down,
   Right,
   Left
}
private DraggedDirection GetDragDirection(Vector3 dragVector)
{
  float positiveX = Mathf.Abs(dragVector.x);
  float positiveY = Mathf.Abs(dragVector.y);
  DraggedDirection draggedDir;
  if (positiveX > positiveY)
  {
    draggedDir = (dragVector.x > 0) ? DraggedDirection.Right : DraggedDirection.Left;
  }
  else
  {
    draggedDir = (dragVector.y > 0) ? DraggedDirection.Up : DraggedDirection.Down;
  }
    Debug.Log(draggedDir);
    return draggedDir;
}

As you can see is very easy. Uf you want to know more you can download the full source code in the article.
The main advantages of this system is that It’ll work in both Mobile and non-mobile platforms

8 Likes

Hi Max, the download link in the article no longer seems to work.
Anywhere else I can download it from?
Thanks.

1 Like

This doesn’t work for mobile, does it?

Yes absolutely! Why not?

Ok good to know. Just asking.

So how would you call this?

Add a script Component with the above code (both parts)
Make sure your script has:

    public class PageSwiper : MonoBehaviour, IDragHandler, IEndDragHandler{
      ...
1 Like

I am getting error that those namespaces can’t be found, do I need any new “using …”?

yes, you need “using UnityEngine.EventSystems;”
Microsoft Visual Studio tells you that doesn’t it?
And for this example you probably only need IEndDragHandler since he only has an OnEndDrag in his code.

Legend! Works perfect.!

The code doesn’t work on my machine. Am I missing something?

This was great. For new comers: you need to add a panel and attach the script to it in the hierarchy. You also need an event system component in the hierarchy, for it to work.

Wouldn’t it be better as a Vector2?