Spawning something at time interval

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Bishop
:warning: Old Version Published before Godot 3 was released.

Hi,
I’m spawning a bird at given time in this script.
…this script works fine but I’d like to ask if there is a better solution?
Thanks for answers.

extends Position3D

var bird_time = 0
#------------------------
#------------------------
func _ready():
	set_process(true)
#-----------------------------------------
func _process(delta):
	bird_time += 1
	if bird_time == 5:
		spawn_bird()
	if bird_time == 800:
		bird_time = 0
		return
#------------------------------------------
func spawn_bird():
	var new_bird
	var bird = preload("res://scenes/bird_03.scn")
	new_bird = bird.instance()
	add_child(new_bird)
#-------------------------------------------
:bust_in_silhouette: Reply From: avencherus

You may want to used fixed processing, it has an exact time step.

Also you don’t want to use counters, because they will run at different speeds based on the frame rate. Use the delta time given by the loop. Accumulate it up to some timer value.

func ready():
	set_fixed_process(true)

var bird_spawn_delay = 5.0/60.0

var timer = 0.0

func _fixed_process(delta):
	
	if(timer >= bird_spawn_delay):
		timer -= bird_spawn_delay
		spawn_bird()

	timer += delta

Thanks very much…yes it’s a better solution.

Bishop | 2018-01-01 00:02

:bust_in_silhouette: Reply From: kidscancode

Why not just use a Timer? That’s what they’re for. Set its wait_time, autostart (or start it in code), and connect the timeout() signal:

func _on_Timer_timeout():
    spawn_bird()

Thanks very much too,…i know, I can use Timer for that but I’m learning GDscript so I write scripts as much as I can.

Bishop | 2018-01-01 00:08

I understand that, but you shouldn’t write scripts just to write scripts. There will be plenty of scripting needed in your projects. Save the scripting for the things you need, and use the built-in engine tools - it’s the whole point of using an engine in the first place.

kidscancode | 2018-01-01 00:31

Thank you…you’re right…so, this is the meaning that AnimationPlayer or Timer nodes are faster than writing script - It is clear…but also faster for performance?..because built-in tools?

Bishop | 2018-01-01 18:24

Well, for something like a Timer, you probably wouldn’t see much performance difference, but in general, yes. The engine is written in C++ and many optimizations have been made before it comes to you. Scripting is intended to be the “glue” you use to tie the various components you need together, and to implement your game logic.

kidscancode | 2018-01-01 22:38

Thank you very much for your help and clarifications…i appreciate it.

Bishop | 2018-01-01 23:00