Search code examples
javalibgdxtimingrate

LibGDX - Best way to adjust fire rate in a loop


I'm making a 2D platformer / shooter with LibGDX. I'm having this loop where holding fire-button down causes bullets to fly from the main character's gun the whole duration while the fire-button is pressed down (rapid fire). That part works perfectly and as intended. However, I'd like the rate of fire to be a bit slower. Currently the loop just adds a bullet to the world on each game frame which means the rate of fire is ridiculously high.

I've been trying to find a good way to do this, to no avail. Any suggestions would be vastly appreciated.

the loop:

if (keys.get(Keys.FIRE)) {
    player.setState(State.FIRING);
        world.addBullet(new Bullet(1f,1f,0));
}

Solution

  • You can use a delay mechanism by having a variable which counts down the time and every time it hits 0, you make one shot and reset the time, for example to 0.2f when you want the player to shoot every 0.2s:

    private float fireDelay;
    
    public void render(float deltaTime) {
        fireDelay -= deltaTime;
        if (keys.get(Keys.FIRE)) {
            player.setState(State.FIRING);
            if (fireDelay <= 0) {
                world.addBullet(new Bullet(1f,1f,0));
                fireDelay += 0.2;
            }
        }
    }