+1 vote

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()
in Engine by (243 points)

1 Answer

+1 vote

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.

by (1,577 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.