Search code examples
javadelay

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.


Solution

  • 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