How do I make a simple Timer?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Cobaltiz

I want made a script so when I touch a potion, I am faster. The sprite disappears after I touch it, but after 3 seconds I want my speed value to go back from 1000 to 500.
I have 1000 speed forever if I touch the potion.

Potion code:

extends Sprite

onready var t = get_node("Timer")

func _ready():
	pass 

func hit():
	queue_free()

func _on_Spell_body_entered(body):
	if "Player" in body.name:
		body.movespeed=1000
		$Timer.start()
		hit()
			
func WaitTime():
	t. set_wait_time(3)
	t. set_one_shot(true)
	self. add_child(t)
	t. start()
	yield(t, "timeout")
	get_parent().get_node("Player").movespeed = 500
	queue_free()

Player code:

extends KinematicBody2D

var max_movespeed=500
var movespeed = 500
var bullet_speed = 2000
var max_ammo = 10
var current_ammo = max_ammo 

....

Did you connect the time out signal to your script ?

horsecar123 | 2022-03-19 18:14

:bust_in_silhouette: Reply From: rhennig

You have to connect to the timeout signal to get when the timer runs out.

var timer = Timer.new()

func _ready():
	timer.connect("timeout",self,"do_this")
	timer.wait_time = 3
	timer.one_shot = true
	add_child(timer)
	timer.start()

func do_this():
	print('wait 3 seconds and do this....')

Thank you but when should I change the speed to 1000 and then to 500 again, like in which function

Cobaltiz | 2022-03-19 23:25

before you start your timer you increase the speed, and after the signal you change it back. Using the previous example:

var timer = Timer.new() 

func potion_used():
    timer.connect("timeout",self,"do_this") 
    timer.wait_time = 3
    timer.one_shot = true
    add_child(timer)
    movespeed=1000
    timer.start()

func do_this():
    movespeed=500

rhennig | 2022-03-20 00:05

I tried but it gives me an error

The identifier “movespeed” isn’t declared in the curent scope.

I guess that’s because the movespeed variable it’s in the Player script, while the script you wrote above it’s in Potion script.
Were should I put the code?

Cobaltiz | 2022-03-20 11:27

That was just an example but lets try to adapt it to your code:

At the beginning of your Potion script declare:

var timer = Timer.new() 

Then change this code to:

func _on_Spell_body_entered(body):
    if "Player" in body.name:
        timer.connect("timeout",self,"do_this",[body]) 
        timer.wait_time = 3
        timer.one_shot = true
        add_child(timer)
        body.movespeed=1000
        timer.start()

And add another function:

func do_this(body):
	body.movespeed = 500

rhennig | 2022-03-20 13:19

Yesss finally it worked. I also changed the values a bit and it works like a charm now. Thanks

Cobaltiz | 2022-03-20 14:08