Долгое время нажмите и случайные значения времени - PullRequest
0 голосов
/ 07 октября 2019

Я хочу вызвать событие после нескольких секунд длительного нажатия на сенсорном экране. Я пытаюсь достичь этой цели с помощью следующего кода. Проблема в том, что прошедшее время в некотором роде случайное.

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();
      }
    }
  }
}

Дело в том, что это условие "(timePressed> tim)" никогда не выполняется и idonot не понимает, почему.

1 Ответ

5 голосов
/ 07 октября 2019

Time.time возвращает The time at the beginning of this frame (Read Only). This is the time in seconds since the start of the game..

Фиксированный псевдокод:

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();
  }
}
...