P
PyWhacket27

Best way to setup a cooldown after a Timer ends?

Hi there,

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:

 if Input.is_action_just_pressed("dodge"):

  get_node("DodgeTimer").start()

  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

 yield(get_tree().create_timer(5.0), "timeout")


Is there a better way to accomplish this, or would a Timer node as a child of another Timer node work

  • FATNUT replied

    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:

    Example:

    extends Node2D

    #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:
    func _physics_process(delta):

    #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:
    dodgeTimer.start()
    canDash = false
    self.speed = dashSpeed

    else:
    if Input.is_action_just_pressed("ui_down"):
    print("cant dash right now")




    #Once the DodgeTimer stops, the player will be normal speed and the
    #Cooldown for dodging starts.
    func _on_DodgeTimer_timeout():
    self.speed = normalSpeed
    cooldownDodgeTimer.start()


    #Once the cooldowntimer stops, we enable dashing again.
    func _on_CooldownDodgeTimer_timeout():
    canDash = true


    Scene Setup:


    DodgeTimer:


    CooldownDodgeTimer:

    1 love
  • P
    PyWhacket27 replied

    Appreciate the help here! After posting this, I mulled it over overnight, and then essentially did what you had posted here, though definitely not as gracefully haha. Thanks again for the detailed reply, really appreciate the Godot community! 

    1 love
  • Nathan Lovato replied

    Thanks for helping FATNUT! I can confirm this is the way to go.

    1 love