0

I need to find the angle between the swipe in Unity3D. In the update function I'm using the following code:

private void Update()
{
    if (Input.GetMouseButtonDown(0))
    {
        fingerup=Input.mousePosition;
        fingerdown=Input.mousePosition;
    }
    if (Input.GetMouseButtonUp(0))
    {
        fingerdown=Input.mousePosition;
        CheckSwipe();
    }
}

and in the CheckSwipe function I'm doing this:

    CheckSwipe()
    {
        var directionvector = fingerup-fingerdown;
        if(directionvector.magnitude>SwipeThreshold)
        {
        /* I need to find the angle between the fingerup and the fingerdown vectors and based on that angle I need to check if the user swiped left, right, up or down. */

/*if (angle>= 45 && angle< 135) onSwipeUp.Invoke();
        else if (angle>= 135 && angle < 225) onSwipeRight.Invoke();
        else if (angle>= 225 && angle< 315) onSwipeDown.Invoke();
        else if (angle>= 315 && angle< 360 || angle >= 0 && angle< 45) onSwipeLeft.Invoke();*/
        }
    }

How can I get the angle of swipe? I tried various solutions, but it was not working. Any help from any one is appreciated. Thanks in advance.

njnjnj
  • 978
  • 4
  • 23
  • 58

1 Answers1

0

First thing, during button mouse up event, you should assign value to fingerup variable, not down.

If this doesn't fix your issue, I came up with idea to use trigonometry to calculate the angle:

if (Input.GetMouseButtonDown(0))
        {
            fingerup = Input.mousePosition;
            fingerdown = Input.mousePosition;
        }
        if (Input.GetMouseButtonUp(0))
        {
            fingerup = Input.mousePosition;

            double angle = Mathf.Atan((fingerup.x - fingerdown.x) / (fingerup.y - fingerdown.y)) * Mathf.Rad2Deg;

            if (fingerup.y < fingerdown.y) angle += 180;
            if (fingerup.y > fingerdown.y && fingerup.x < fingerdown.x) angle += 360;

            Debug.Log("fingerDownPos : " + fingerdown + " fingerUpPos: " + fingerup + " angle: " + angle);
        }

Probably it can be written better, but I had no other idea but to use ifs and add angles depending on start and end. Anyway, it's working, and should be a good start.

Edit: your question is about an angle, but I just realized, that since you need only the general direction of a swipe (left, right, up, down) you don't need to calculate angle. Just substract fingerup.x - fingerdown.x and fingerup.y - fingerdown.y Compare which absolute value of this is bigger. If abs from vertical is bigger than horizontal, then it will be either up or down, up if the substraction is greater than 0. You get the idea how to do the rest.

bartol44
  • 562
  • 2
  • 12