长时间按和随机时间值

问题描述 投票:-1回答:1

我想在触摸屏上长按几秒钟后触发事件。我正在尝试通过以下代码实现此目标。问题在于,从某种程度上讲,经过的时间是随机的。

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)”从不成立,并且不了解原因。

unity3d touch
1个回答
1
投票

[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 (_timePressed > _maxTimeTreshold)
  {
    Application.Quit();
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.