0

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?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
karoma
  • 1,548
  • 5
  • 24
  • 43

2 Answers2

1

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;
     }
  }
}
Jack
  • 131,802
  • 30
  • 241
  • 343
  • He's talking about 2 shoots per second, I don't think that `nanoTime() `would make so much difference in this case. – Jack Feb 04 '13 at 18:12
  • I was thinking of something along those lines but for some reason I thought it would be a lot more complicated. And yes, I don't need ultra accuracy with the timing so milliseconds are fine. Thank you kindly. – karoma Feb 04 '13 at 18:17
0

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.

Skip Head
  • 7,580
  • 1
  • 30
  • 34
  • Traditionally yes, but there's a bit more going on in this game which requires a slightly higher rate of fire. – karoma Feb 04 '13 at 18:18