How do I repeat the action after the key has been held down for a specified amount of time?

I am currently developing in XNA / C #. When the user presses the ( Keys.Right

) key , I need to move the object. I want this to happen

  • when the user presses a key
  • after 1 second while the user holds the key, and then every 0.25 seconds.

I've already implemented the first one:

_kbOld = _kbNew;
_kbNew = _kb.GetState();
if(_kbNew.IsKeyDown(Keys.Right) &&
   _kbOld.IsKeyUp(Keys.Right))
{
    //Do something
}

      

How would I do other things? I had the following ideas:

  • A Queue<KeyboardState>

    , tracking the last KeyboardState

    s

  • Saving the time of the last key press and release ( GameTime

    )

It should work like text input on Windows: when you hold a letter, it will repeat after a certain amount of time.

What order should I use? Do you have any other ideas?

Thanks in advance!

+3


source to share


3 answers


I would just keep the last press like you said:



if (IsPressed())
{
    // Key has just been pushed
    if (!WasPressed())
    {
        // Store the time
        pushTime = GetCurrentTime();

        // Execute the action once immediately
        // like a letter being printed when the button is pressed
        Action();
    }

    // Enough time has passed since the last push time
    if (HasPassedDelay())
    {
        Action();
    }   
}

      

+2


source


I remember doing something like this in javascript which



  • you create a timer, set its interval to 1 second and then turn it on in the mousedown (keydown in your case). You will reset and disable it on activation.
  • The second step is to wire your behavior to the Tick () event.
  • The third step is to check inside the Tick () handler if the Keys.Right state is not working, and if not, reset the timer.
0


source


I suggest you create your own Key and Keyboard class. In Keyboard, you can create an updateInput () method that will update the state of each key, where you can use functions like this. In the Key class, you can use

Keeping the time of the last keystroke and when it was released (GameTime)

@JuannStrauss Definitely not a timer.

0


source







All Articles