2

I've been working on my game and now, my player needs to shoot. He does shoot but to decrease the ammo, it keeps decreasing as long as I hold the space bar. I'd like to know a code that lets me remove -1 ammo each time the spacebar is pressed and even if it's still pressed. Thanks, hope you answer me soon!

James Walsh
  • 3
  • 1
  • 3
  • 2
    show some code that you have tried, that will help us to give you proper direction. – Smit Dec 15 '12 at 23:24

1 Answers1

2

On key down, initialize and start a java.util.Timer with initial delay 0 and delay X (however frequently you want to fire.

On key up, stop the timer.

Michael Brewer-Davis
  • 14,018
  • 5
  • 37
  • 49
  • +1, although I would recommend using `java.swing.Timer` instead (assuming there's some sort of painting involved - which is probably the case for OP). Using `java.swing.Timer` is generally preferred over `java.util.Timer` when it comes down to Swing-related business. EDIT: On the other hand, as OP will probably use the timer in a `KeyListener`, execution will already take place on the EDT and thus the use of `java.util.Timer` might suffice. – Priidu Neemre Dec 15 '12 at 23:42
  • 1
    @Priidu: no. The whole point of a java.util.Timer is to execute something in another thread, after some delay. So a Swing timer is necessary if the eecuted action must be on the EDT. – JB Nizet Dec 15 '12 at 23:47
  • I'd default to off the EDT, with the view invalidated and redrawn. But I've never been a game developer. In any case, I agree with @Priidu if you want to keep your work on the EDT. – Michael Brewer-Davis Dec 16 '12 at 00:19
  • I dont really know how I should do this. If you know how to, let me know. Thx for the help btw! – James Walsh Dec 16 '12 at 01:30
  • Check out @aioobe's answer on http://stackoverflow.com/questions/5199581/java-keylistener-keypressed-method-fires-too-fast (And never stop thinking about that EDT.) – Michael Brewer-Davis Dec 16 '12 at 04:12
  • Thx, I looked at it and I know what you mean now! Thx a lot! – James Walsh Dec 16 '12 at 19:45