1
\$\begingroup\$

This is my swipe detection code. This code uses touch input. I want to do this using the left mouse button. So basically I want to 'swipe' using the mouse.How can I achieve that?

public float maxTime;
public float minSwipeDist;

float startTime;
float endTime;

Vector3 startPos;
Vector3 endPos;
float swipeDistance;
float swipeTime;

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
    if(Input.touchCount > 0) {
        Touch touch = Input.GetTouch(0);
        if (touch.phase == TouchPhase.Began)
        {
            startTime = Time.time;
            startPos = touch.position;
        }
        else if (touch.phase == TouchPhase.Ended)
        {
            endTime = Time.time;
            endPos = touch.position;

            swipeDistance = (endPos - startPos).magnitude;
            swipeTime = endTime - startTime;

            if(swipeTime < maxTime && swipeDistance>minSwipeDist)
            {
                SwipeFunc();
            }
        }
    } 
}

void SwipeFunc()
{
    Vector2 distance = endPos - startPos;
    if(Mathf.Abs(distance.x) > Mathf.Abs(distance.y))
    {
        Debug.Log("Horizontal swipe");
    }
    else if (Mathf.Abs(distance.x) < Mathf.Abs(distance.y))
    {
        Debug.Log(" vertical  swipe");
    }
}
}
\$\endgroup\$
1
  • \$\begingroup\$ You can use my solution from Github (or learn it) - it easely detects any swipes, on a mouse or touch input. Video tutorial and WebGL working demo included in description ;) \$\endgroup\$ Feb 17, 2020 at 13:01

1 Answer 1

1
\$\begingroup\$

You need to handle mouse input. Currently you are only handling Touch input.

//if(Input.touchCount > 0) { }
if (Input.GetMouseButton()) { }

//if (touch.phase == TouchPhase.Began) { }
if (Input.GetMouseButtonDown()) { }

//else if (touch.phase == TouchPhase.Ended) { }
else if (Input.GetMouseButtonUp()) {}

//touch.position;
Input.mouseposition;

Then it would be up to you to either code this in a seperate component, or include it in the same with an if statement, or use precompiler instructions.

The point is, in order for you to be able to do this with Mouse Input, you need to handle the mouse input. The rest of the code should work fine.

\$\endgroup\$
3
  • \$\begingroup\$ should I replace add if (Input.GetMouseButton(0)) { } instead of if (Input.GetMouseButton()) { } and remove Touch touch = Input.GetTouch(0); \$\endgroup\$
    – kp21
    Jul 27, 2016 at 6:31
  • \$\begingroup\$ It says ArgumentException - Index out of bounds when I swipe. \$\endgroup\$
    – kp21
    Jul 27, 2016 at 6:37
  • \$\begingroup\$ after some adjustments, I managed to remove the error. But when I swipe nothing is happening (no log messages). \$\endgroup\$
    – kp21
    Jul 27, 2016 at 8:39

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .