- Home /
How to disable a keypress after a certain amount of time?
I have a button that gives the player a speed boost, but I only want it to last for a short amount of time (like a second). I'm trying to use a Coroutine to make it last only a second, but it's not working right.
My Code:
IEnumerator SpeedUpBoost () {
yield return new WaitForSeconds (speedUpCutoffTime);
rigbody.velocity = new Vector2 (speed, 0);
}
// Update is called once per frame
void Update () {
if (updateOn == true) {
if (Input.GetKey (moveUp)) {
rigbody.velocity = new Vector2 (speed, 20);
} else if (Input.GetKey(speedUp)) {
rigbody.velocity = new Vector2 (speed, 40);
StartCoroutine (SpeedUpBoost ());
} else if (Input.GetKey (speedDown)) {
rigbody.velocity = new Vector2 (speed, -20);
} else {
rigbody.velocity = new Vector2 (speed, 0);
}
}
}
Any ideas on what to do what be super helpful! Thanks! :D
Answer by Jessespike · Sep 09, 2016 at 06:17 PM
WaitForSeconds will pause the coroutine, you can use WaitForEndOfFrame and Time.deltaTime to keep track of time progress. Can try something like this:
bool boostAvailable = true;
IEnumerator SpeedUpBoost () {
updateOn = false;
boostAvailable = false;
float elapsed = 0f;
while (elapsed < speedUpCutoffTime)
{
rigbody.velocity = new Vector2 (speed, 40);
elapsed += Time.deltaTime;
yield return new WaitForEndOfFrame();
}
updateOn = true;
// simple cooldown, prevent boost for some time
// if an item makes the boost available, then it can set boostAvailable to true instead.
yield return new WaitForSeconds(5f);
boostAvailable = true;
}
// Update is called once per frame
void Update () {
if (updateOn == true) {
if (Input.GetKey (moveUp)) {
rigbody.velocity = new Vector2 (speed, 20);
} else if (Input.GetKey(speedUp) && boostAvailable) {
StartCoroutine(SpeedUpBoost());
} else if (Input.GetKey (speedDown)) {
rigbody.velocity = new Vector2 (speed, -20);
} else {
rigbody.velocity = new Vector2 (speed, 0);
}
}
}
Wow that worked like a charm. Thank you so much!! I was thinking I needed to incorporate Time.deltatime into it somehow, I just wasn't sure how. :D
Your answer
Follow this Question
Related Questions
Audio playing problem 1 Answer
Input.GetKey not working 1 Answer
Setting position after respawn. 0 Answers
GetKey/GetKeyDown, Paired with Adjusting Stats 1 Answer
physics randomness problem 2 Answers