Java – libgdx – the best way to adjust the flame rate in the cycle
I'm making 2D platform games / shooting games with libgdx I'm doing this cycle. Pressing and holding the fire button will cause the bullet to fly out of the protagonist's gun for the whole duration, while pressing the button (quick shot) This part is perfect and works as expected However, I hope the fire will be a little slower At present, the cycle only adds one bullet to the world on each game frame, which means that the speed is ridiculously high
I've been trying to find a good way to do this, but to no avail Any suggestion will be highly appreciated
Cycle:
if (keys.get(Keys.FIRE)) { player.setState(State.FIRING); world.addBullet(new Bullet(1f,1f,0)); }
Solution
You can use a delay mechanism to reduce the time through a variable. Each time you hit 0, you shoot once and reset the time. For example, when you want the player to shoot every 0.2 seconds, it is 0.2f:
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,0)); fireDelay += 0.2; } } }