Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

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

Discussion in '2D' started by humfrey, May 23, 2016.

  1. humfrey

    humfrey

    Joined:
    May 23, 2016
    Posts:
    12
    I want to do something when the spacebar is pressed twice with a second. How can I recognise this input?
     
  2. LiterallyJeff

    LiterallyJeff

    Joined:
    Jan 21, 2015
    Posts:
    2,807
    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.

    Code (CSharp):
    1. public float doubleTapTime = 1f;
    2. private float elapsedTime;
    3. private int pressCount;
    4.  
    5. private void Update()
    6. {
    7.     // count the number of times space is pressed
    8.     if(Input.GetKeyDown(KeyCode.Space))
    9.     {
    10.         pressCount++;
    11.     }
    12.  
    13.     // if they pressed at least once
    14.     if(pressCount > 0)
    15.     {
    16.         // count the time passed
    17.         elapsedTime += Time.deltaTime;
    18.  
    19.         // if the time elapsed is greater than the time limit
    20.         if(elapsedTime > doubleTapTime)
    21.         {
    22.             resetPressTimer();
    23.         }
    24.         else if(pressCount == 2) // otherwise if the press count is 2
    25.         {
    26.             // double pressed within the time limit
    27.             // do stuff
    28.             resetPressTimer();
    29.         }
    30.     }
    31. }
    32.  
    33. //reset the press count & timer
    34. private void resetPressTimer(){
    35.     pressCount = 0;
    36.     elapsedTime = 0;
    37. }
    38.  
    39.  
     
    Last edited: May 23, 2016
  3. humfrey

    humfrey

    Joined:
    May 23, 2016
    Posts:
    12


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