Brandyn
Brandyn

Reputation: 11

Adding a delay between shots(key presses)

I have a game where you can fire bullets by adding the bullets to the Controller class when a key is pressed. Here is the code from KeyPressed();

else if (key == KeyEvent.VK_Q && !is_shooting)
    {
        is_shooting = true;
        c.addBullet(new Bullet(p.getX(), p.getY(), this));
    }

from KeyRealeased:

        else if (key == KeyEvent.VK_Q)
    {               
        is_shooting = false;
    }

As is, you can shoot as much as you want, the is_shooting just stops from holding the key down. I would like it so that after you shoot there is a cooldown before you can take your next shot. I tried using Thread.Sleep but that will also make it so that the character can't move during the cooldown. Any help is appreciated.

Upvotes: 0

Views: 882

Answers (2)

MadProgrammer
MadProgrammer

Reputation: 347194

With such little context to go on, it's difficult to be 100% what the best solution would be to your immediate problem.

One thing I've done in the past is, record the time when a particular event is triggered, compare the difference in time to the last time it was triggered and if some time threshold has past, allow the action to occur, otherwise ignore it

Something like...

long timeNow = System.currentTimeMillis();
long time = timeNow - timeOfLastProjectile;
if (time < 0 || time > 1000) {
    timeOfLastProjectile = timeNow;
    // Trigger associated action
}

as an example.

One reason I might use this approach is if I have a lot of incoming events which need to be process and don't want to fire off a new thread or Timer in order to manage system resources, but that kind of decision requires additional context to the problem.

Also agree with Hovercraft Full Of Eels, you'd be better of using the Key Bindings API

Upvotes: 1

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

Your code looks to be from a Swing GUI -- you don't say, but really should as it is key information and if not true, would completely change the approach. If this is true, then don't use Thread.sleep since if called on the GUI's event thread would put the entire GUI to sleep rendering it useless. Instead use a Swing Timer (please check the Swing Timer Tutorial for more). Instead of a for loop, the Timer's ActionListener's actinPerformed method would be called repeatedly until you call stop() on the Timer.

Side issue: if this is a Swing GUI, you're likely better off using Key Bindings and not a KeyListener. More on that here: Key Bindings Tutorial

Upvotes: 1

Related Questions