Search code examples
c#unity-game-engineinputgestures

How to check if a touch in Unity is being moved back and forth within a range?


I am trying to figure out how to detect when a touch is being moved back and forth in Unity.

so as the image shows, I am looking for a way to detect when the touch moves from its starting position (1) to the second x (2), then back to somewhere near the starting position (3) all with a certain speed and within a time frame, essentially something like a shaking gesture. Im really stuck as to how to do this. Any help will be greatly appreciated.

an illustration of what I mean

so far I just know how to get the starting position with a touch.

Vector2 startingPos;
float shakeTime = 2f;

void Update()
{
    foreach(Input.touch touch in Input.touches)
    {
       if(touch.phase == TouchPhase.Began)
       {
          startingPos = touch.position;
       }
    }
}

Solution

  • float touchTimer=0f;
    float shakeTime = 2f;
    float moveAwayLimit = 1f;
    float moveBackLimit = .5f;
    bool awayReached = false;
    Vector2 startingPos;
    
    void Update()
    {
        foreach (Touch touch in Input.touches)
        {
            if (touch.phase == TouchPhase.Began)
            {
                startingPos = touch.position;
                touchTimer = 0;
                awayReached = false;
            }
            if (Vector2.Distance(touch.position, startingPos) > moveAwayLimit && touchTimer < shakeTime && !awayReached)
            {
                awayReached = true;
            }
            else if (Vector2.Distance(touch.position, startingPos) < moveBackLimit && touchTimer < shakeTime && awayReached)
            {
                Shake();
            }
            touchTimer += Time.deltaTime;
        }
    }
    

    Something like this should work, it checks if you move away further than moveAwayLimit from the start, and after that if you're within moveBackLimit from the startingPos.