Search code examples
javaawtkeylistenerkeyevent

How to restrict KeyEvent capture speed


I'm making a fairly basic top down 2D shooting game (think Space Invaders) but I'm having an issue with KeyEvent processing too many events per second.

I have this:

if (e.getKeyCode() == KeyEvent.VK_SPACE){
    shoot();
}

shoot() creates a bullet and sets it firing upward, but a problem arises if you simply hold down space to fire hundreds of bullets, making the game trivial.

Is there a way to make it process only one or two keypresses per second, ignoring the rest?


Solution

  • You could use a handmade timer so that it will be either lightweight either easily customizable, something like:

    long lastShoot = System.currentTimeMillis();
    final long threshold = 500; // 500msec = half second
    
    public void keyPressed(KeyEvent e) { 
      if (e.getKeyCode() == KeyEvent.VK_SPACE)
      {
         long now = System.currentTimeMillis();
         if (now - lastShoot > threshold)
         {
           shoot();
           lastShoot = now;
         }
      }
    }