Search code examples
unity-game-enginetouch

Long time press and random time values


I want to trigger an event after tot seconds of long press on a touch screen. I'm trying to achieve this goal with the following code. The problem is that the time that has passed is, in some way, random.

private float timePressed = 0.0f;
private float timeLastPress = 0.0f;
public  float timeDelayThreshold = 2.0f;

void Update() {
  checkForLongPress(timeDelayThreshold);
}

void checkForLongPress(float tim) {
  for (int i = 0; i < Input.touchCount; i++)
  {
    if (Input.GetTouch(0).phase == TouchPhase.Began)
    {
      // If the user puts her finger on screen...
      Debug.Log("Touch start");
      timePressed = Time.time - timeLastPress;
    }

    if (Input.GetTouch(0).phase == TouchPhase.Ended)
    {
      // If the user raises her finger from screen
      timeLastPress = Time.time;
      Debug.Log("Releasing Touch");
      Debug.Log("Time passed --> " + timePressed);
      if (timePressed > tim)
      {
        Debug.Log("Closing APP");
        // Is the time pressed greater than our time delay threshold?
        Application.Quit();
      }
    }
  }
}

The Fact is that this condition "(timePressed > tim)" is never true and i do not understand why.


Solution

  • Time.time returns The time at the beginning of this frame (Read Only). This is the time in seconds since the start of the game..

    Fixed pseudo code:

    if (Input.GetTouch(i).phase == TouchPhase.Began)
    {
      _timePressed = Time.time;
      return;
    }
    if (Input.GetTouch(i).phase == TouchPhase.Ended)
    {
      var deltaTime = Time.time - _timePressed;
      if (deltaTime > _maxTimeTreshold)
      {
        Application.Quit();
      }
    }