Cooldown
Type: GeneralA reusable cooldown for shooting, dashing or any ability. Ask try_use() and it only says yes when the cooldown is over.
Setup
- Save the script as cooldown.gd.
- Add a Node as a child of your character, attach the script and name it after the ability, for example ShootCooldown.
- Set Duration in the Inspector.
- Wrap the ability in an if that calls try_use().
Code
GDScript
class_name Cooldown
extends Node
## A reusable cooldown. try_use() returns true only when the cooldown is over.
signal ready_again
@export var duration: float = 0.5
var _time_left: float = 0.0
func _process(delta: float) -> void:
if _time_left <= 0.0:
return
_time_left -= delta
if _time_left <= 0.0:
ready_again.emit()
func is_ready() -> bool:
return _time_left <= 0.0
func try_use() -> bool:
if not is_ready():
return false
_time_left = duration
return trueUsage example
GDScript
# player.gd
@onready var shoot_cooldown: Cooldown = $ShootCooldown
func _process(_delta: float) -> void:
if Input.is_action_pressed("shoot") and shoot_cooldown.try_use():
spawn_bullet()