Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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));
}
like image 510
Steve Waters Avatar asked Oct 21 '25 14:10

Steve Waters


2 Answers

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;
        }
    }
}
like image 166
noone Avatar answered Oct 23 '25 07:10

noone


Use a constant to hold the fire rate and add a timing mechanism, like so:

public static final long FIRE_RATE = 200000000L;
public long lastShot;

if(System.nanoTime() - lastShot >= FIRE_RATE) {
    world.addBullet(new Bullet(1f,1f,0));
    lastShot = System.nanoTime();
}
like image 38
Someone Avatar answered Oct 23 '25 08:10

Someone