简体   繁体   中英

How to check if key has been clicked more than once or to find out how long a key has been pressed for c#

if(GetComponent<Rigidbody2D>().position.y >= -2.4){
     abletojump = false;
}
else{
    abletojump = true;
}
if(abletojump == true && Input.GetKey("space")){
     transform.Translate(Vector3.up * 10 * Time.deltaTime);
}

I have made it so that if the object is over a specific height they shouldn't be allowed to jump. But it seems that when ever I set that height range it always seems to go lower than that so it repeatedly keeps jumping in the air. anyways knowing how to tell if a key has been pressed the an amount of times or to detect how long a key has been pressed for would really help.

Thanks.

Save the time when button is pushed Input.GetKeyDown and while the button is held down Input.GetKey find the difference between currentTime and the time that the button was pushed.

float timeThatshouldBePassed = 5f;

void Update() {
  if (Input.GetKeyDown(KeyCode.Space)) {
    float pushStart = Time.time;
  }
  if (Input.GetKey(KeyCode.Space)) {
    if (Time.time - pushStart > timeThatshouldBebPassed) {
      // doSomethings
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM