how to recognise the space bar tapped/pressed twice within a second

I want to do something when the spacebar is pressed twice with a second. How can I recognise this input?

Here is just one of many ways to do this.

Every frame I’m checking if the space bar was pressed, and counting the number of times it was pressed.

If the spacebar has been pressed at least once, I start adding Time.deltaTime each frame. (Time.deltaTime is the amount of time passed each frame, usually a very small number).

If that elapsed time surpasses the limit (1 second), I reset the press counter and elapsed time variable.

If the elapsedTime has not surpassed the limit, and the pressCount is 2, then a double tap was performed within the time limit.

public float doubleTapTime = 1f;
private float elapsedTime;
private int pressCount;

private void Update()
{
    // count the number of times space is pressed
    if(Input.GetKeyDown(KeyCode.Space))
    {
        pressCount++;
    }
  
    // if they pressed at least once
    if(pressCount > 0)
    {
        // count the time passed
        elapsedTime += Time.deltaTime;

        // if the time elapsed is greater than the time limit
        if(elapsedTime > doubleTapTime)
        {
            resetPressTimer();
        }
        else if(pressCount == 2) // otherwise if the press count is 2
        {
            // double pressed within the time limit
            // do stuff
            resetPressTimer();
        }
    }
}

//reset the press count & timer
private void resetPressTimer(){
    pressCount = 0;
    elapsedTime = 0;
}
5 Likes

Thank you very much especially for taking time to give such a detailed explanation.

1 Like