Question

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));
}
Was it helpful?

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;
        }
    }
}

OTHER TIPS

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();
}

I have seen @noone s answer and it is correct. I just answer you, because i had to add the same to my game. What i did: I had a variable boolean attacking, which stores if you are holding firebutton. Then i had 2 more variables: float bps, which stores how many bullets you can shoot per second and float reloadTime, which stores how long it takes to reload an empty magazin, if you use one. I also store a long time and a boolean reloading. Time stores the TimeUtils.millis() of your last shot, the reloading stores if you are reloading the magazin or just shooting. Then in the attack method i call a method: public boolean readyToAttack(), in which i compare TimeUtils.millis() to my variable time. If reloading = true, TimeUtils.millis() - reloadTime has to bigger then time. If not, TimeUtils.millis() - (1000 / bps) has to be bigger then time. If this is the case the method returns true and i can shoot. Noones solution is simpler, but for me bps is easier to understand so i used this. Hope it helps

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top