- Home /
How to check for rapid key presses?
I've finally created a movement script I like, but now i'd like to add another little feature to it.
I'm just wondering if there was any way to make my character move at a fixed rate based on multiple key presses.
ex. I rapidly hit my forward button, W. I want the script to notice when I have pressed the key 4 times within 1 second.
Is this possible? And how would I go about doing this?
It's possible. You already have your problem well defined: check if the W-key is pressed 4 times within one second.
Next you need to figure out:
how to check for keypresses.
how to deter$$anonymous$$e if 1 second has passed.
Once you know how to achieve both of these, counting the presses within that second is a simple task.
Answer by Aram-Azhari · Nov 19, 2013 at 07:07 AM
You do something like:
...
public yourClass : Monobehavior
{
public float firstWpress=0;
public int count=0;
void Update()
{
// Check for the W key.
if (Input.GetKeyDown(KeyCode.W))
{
// The current time
var currentTime=Time.time;
// Is this the first time W was pressed?
if (count==0)
{
firstWpress=Time.time; // Save the time of first
}
count++; // increase the key count.
if (count==4) // has the key been pressed 4 times?
{
count=0; // Reset the counter
if (currentTime-firstWpress<1) // was it under 1 second?
{
// It was pressed 4 times within a second
// Do your logic here.
}
}
if (currentTime-firstWpress>1) // Reset the counter if it's been longer that 1 second.
{
count=0;
}
}
}
}
I haven't tried the code, but I hope that would give you some idea.