Godot Version
gdscript
extends Node2D
const BULLET = preload(“res://Scenes/bullet.tscn”)
@onready var muzzle : Marker2D = $Marker2D
@onready var gun: Sprite2D = $Sprite2D
func _process(delta: float) → void:
look_at(get_global_mouse_position())
rotation_degrees = wrap(rotation_degrees, 0, 360)
if rotation_degrees > 90 and rotation_degrees < 270:
scale.y = -1
else:
scale.y = 1
if Input.is_action_just_pressed("Mouse1"):
var bullet_clone = BULLET.instantiate()
get_tree().root.add_child(bullet_clone)
bullet_clone.global_position = muzzle.global_position
bullet_clone.rotation = rotation
Question
Could anyone help so there's a slight delay between shots?
You could do this with a Timer
. Add a Timer
node to your scene, then add a reference to it in your script. Connect the timer’s timeout
signal to a function where you set some boolean that determines whether you can fire or not:
extends Node2D
@export var timer : Timer = null
var cooldown_active : bool = false
func _ready()->void:
timer.timeout.connect(_on_timer_timeout.bind())
func _on_timer_timeout()->void:
cooldown_active = false
Set the timer node via the inspector. You can now use cooldown_active
to selectively execute code:
if Input.is_action_just_pressed("Mouse1"):
if cooldown_active:
return
else:
var bullet_clone = BULLET.instantiate()
get_tree().root.add_child(bullet_clone)
bullet_clone.global_position = muzzle.global_position
bullet_clone.rotation = rotation
cooldown_active = true
timer.start()
You should make sure the timer’s one shot property is set and that autostart is not set.
e: the ‘slight’ delay in this code is the timer’s default value, which is one second.