I'm in the early workings of my 2D game and was hoping to get some help. I have a dodge/dash with a timer that lets the player dodge/dash for 0.3 seconds, and then once that ends, speed returns to normal. I'm trying to create a cooldown timer to start once that 0.3 timer ends. I have tried putting a Cooldown timer as a child node of the Dodge timer, but that didn't end up working out, so now I have tried to create a timer via GDScript. The code I have is:
func dodge() -> void:
speed = dodge_speed
collision_layer = 0
collision_mask = 0
func _on_DodgeTimer_timeout() -> void:
speed = normal_speed
collision_layer = start_collision_layer
collision_mask = start_collision_mask
Is there a better way to accomplish this, or would a Timer node as a child of another Timer node work
The problem with yield is, you have no control over stopping the timer. In a situation where you want to control the cooldown (through upgrades or an item that instantly removes the cooldown) you won't get far with yield. A variable that you enable / disable is a bit more clear.
I recommend adding a Node to your player and keep it as a container for Timers.
There you can add all the Timers you need and can easily reference them in your script:
#Getting the Timers from our Scene Setup:
onready var dodgeTimer = get_node("Node/DodgeTimer")
onready var cooldownDodgeTimer = get_node("Node/CooldownDodgeTimer")
var speed = 0
var normalSpeed = 100
var dashSpeed = 500
var canDash = true
#Basic Input for testing purpose:
#If we press the dash button and canDash is == true, we dash and disable the Dash temporarily.
if Input.is_action_just_pressed("ui_down") && canDash:
canDash = false
self.speed = dashSpeed
print("cant dash right now")
#Once the DodgeTimer stops, the player will be normal speed and the
#Cooldown for dodging starts.
self.speed = normalSpeed
#Once the cooldowntimer stops, we enable dashing again.
canDash = true