- Home /
Need delayed reaction after key press
I need to do a delayed reaction after a key press, here is my current setup:
function turn(dir:float)
{
if(collided==false){
if(dir==-1){
transform.Translate(Vector3.right * Time.deltaTime * -1.50);
}
else if(dir==1){
transform.Translate(Vector3.right * Time.deltaTime * 1.50);
}
}
}
timer = Random.Range(0.45,0.95);
//timerGo() is just WaitForSeconds(timer)
//turn() translates the object left or right by 3
if (Input.GetKey(KeyCode.A)){
timerGo(timer);
turn(-1);
}
if (Input.GetKey(KeyCode.D)){
timerGo(timer);
turn(1);
}
I need the delay to happen and then the move for as long as the user holds the key. However currently whats happening is when the user presses a key it starts the timer after it finishes it moves translates over 1.5. Then the timer starts again with a new value and translates over 1.5, and again, and again.
Answer by erick_weil · Feb 15, 2014 at 04:57 PM
//tryout this:
var countdown : float;
var timer : float;
function turn(dir:float)
{
if(collided==false){
if(dir==-1){
transform.Translate(Vector3.right * Time.deltaTime * -1.50);
}
else if(dir==1){
transform.Translate(Vector3.right * Time.deltaTime * 1.50);
}
}
}
function Update()
{
//now every key press a new delaytime will be set
if(Input.GetKeyDown(KeyCode.A)||Input.GetKeyDown(KeyCode.D)||Input.GetKeyUp(KeyCode.A)||Input.GetKeyUp(KeyCode.D))
{
timer = Random.Range(0.45,0.95);
countdown = 0;
}
if (Input.GetKey(KeyCode.A)){
countdown += Time.deltaTime;
if(countdown >timer)
turn(-1);
}
if (Input.GetKey(KeyCode.D)){
countdown += Time.deltaTime;
if(countdown >timer)
turn(1);
}
}
if you see, I don't used your timerGo() function, waht happens now is a delay before execute the action of turn to left or turn to right
I actually tried a similar solution, and it didn't work. I just tried yours and it also doesn't work, now there is no delay. If I Debug.Log(countdown) it just says 0 one time and that's it.
this worked fine to me... you have missed the update function? see tha in my code, the countdown is into update()
you probably is missing the variables declaration on top:
//tryout this:
var countdown : float;
var timer : float;
.
.
.
this NEED to works, it worked all fine to me
Oddly enough I did have it but I re copy and pasted your and it started working, i guess I missed something. But I ended up removing that mechanic from the game because it became to hard.
I'd appreciate it if you tried it out!
http://dl.dropboxusercontent.com/u/268133971/DrunkDriving/DrunkDriving.html