简体   繁体   中英

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?

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;
     }
  }
}

In that type of game, isn't it usual that there is only one bullet allowed on the screen a time? Don't allow shooting until the current bullet has hit something or disappeared off the top of the screen.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM