Search code examples
c#inputunity-game-enginexnatap

Detecting long press with Unity with distance


I am currently looking for a solution to detect a long press and a tap, but I'm kind of lost, I know it has something to do with deltaPosition or deltaTime.

Can someone explain to me? I'm new with Unity.

It's for dragging a button, so I would press the button for a couple of frames, and if I drag it a couple of pixels it would enter in the DRAG_STATE, if I tap it it would go into TAPPED_STATE.

Notes :

  • I have to detect the distance too

  • I can't use the "Touch" functions, I need to simulate it with the mouse


Solution

  • When you detect the press, then you store the position. On following frames, you check if the position has changed:

    Vector3 position;
    void Update(){
        if(Input.GetMouseButtonDown(0)) { this.position = Input.mousePosition;}
        else if(Input.GetMouseButton(0)){ 
            float distance = Vector3.Distance(this.position, Input.mousePosition);
        } 
        else if(Input.GetMouseButtonUp(0)) { this.position = Vector3.zero }
    }
    

    So on enter, you just record the position, this is when the user presses down the button. Nothing else happens on that frame.

    Next frame, if the user keeps pressing, we compare the previous (initial) position and the current one. This is where you should pass that distance wherever it is needed. If distance is small enough, you would discard the drag or ignore it.

    Finally, when the user releases the button, we reset to 0. You may want to reset to some negative value to make sure the value is not a usable value (tho 0 is unlikely it is not impossible).