Is there a better method for this?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By lincolnpepper

I am making a space shooter game, and i want it so that you can press the button to fire any time (as long as the amount of bullets on screen are less than or equal to 2) but if you hold the button down it will fire the bullets at a steady pace determined by a fire cooldown timer ‘HoldFireTimer’, but i don’t want you pressing the button to fire to be limited by the timer. I have this code for it and it works, but there is no way that this is the best way to do it. Does anyone know a cleaner more efficient way of doing it? This is honestly annoying me with all its messiness and copy+paste.

func _input(event):
	if event.is_action_pressed('fire') and get_node("Muzzle/Bullets").get_child_count() < 2:
		var bullet = preload("res://Scenes/Bullets&Projectiles/Player Bullet.tscn")
		var b = bullet.instance()
		get_node("Muzzle/Bullets").add_child(b)
		b.set_position(position + $Muzzle.position)
		$HoldFireTimer.start()

func _on_HoldFireTimer_timeout():
	if Input.is_action_pressed('fire') and get_node("Muzzle/Bullets").get_child_count() < 2:
		var bullet = preload("res://Scenes/Bullets&Projectiles/Player Bullet.tscn")
		var b = bullet.instance()
		get_node("Muzzle/Bullets").add_child(b)
		b.set_position(position + $Muzzle.position)
		$HoldFireTimer.start()
:bust_in_silhouette: Reply From: Diet Estus

The first thing that comes to my mind is to work with both the action_just_pressed() and action_pressed() methods.

Here is some pseudo-code:

# the fire button was just pressed
if Input.action_just_pressed("fire"):
    if bullet_count < 2:
       fire()
       last_fire_time = now
# the fire button is held
elif Input.action_pressed("fire"):
   if bullet_count < 2:
       if now - last_fire_time > cooldown:
           fire()
           last_fire_time = now    

I didn’t test this method, so you might have to fiddle with it a bit.