How to run a script independent of frames?

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

I have a maze-like game with enemies moving in a grid based on the player’s position on the grid. Enemies can be in a “moving” state where they continue in the same direction or a “not moving” state where, for one frame, they ask for their next direction and then begin moving that way.

An “Instructor” script generates the next direction for each enemy independently of the script that moves each enemy. However, when the “Instructor” runs there is a noticeable lag in the game. Ideally, this script would run over the course of several frames in the “moving” state. Is there a way I can tell Godot to make this script a low-priority and not interfere with the game physics?

Enemy

extends KinematicBody2D
func _ready():
	set_fixed_process(true)

func _fixed_process(delta):
	if is_moving:
		# keep moving
	if not is_moving:
		# get directions from instructor

Instructor

extends Node2D
func _ready():
	# starts a timer

func _on_Timer_timeout():
	# calculate next direction for each enemy that needs one

I’m very new to game development, and while I’ve been able to find answers to most things online, I can’t figure this one out. Thanks!

A typical solution for this problem would be using another thread:

Thread — Godot Engine (latest) documentation in English

Multithreading will not always be simple though.

If the process can be split into multiple units then there’s also the “yield” function:
@GDScript — Godot Engine (latest) documentation in English

You could then call the resume function periodically from outside (another timer or fixed process).

(Oh, I see that you’re probably using godot 2.x but the links are for 3.x. Anyway I know that yield is also available in 2.x and maybe also the Thread class.)

Finally: You should ask yourself why the instructor function is so slow and if there’s a better and faster algorithm.

wombatstampede | 2019-02-12 08:44

What do you mean by lag? Is it taking too much CPU or is it simply delayed? If there is pathfinding at stake maybe threads can improve things, but depending on what you actually do in the instructor, there might be other solutions.

Zylann | 2019-02-12 13:43

I will try getting threads to work. It’s not taking too much CPU nor is it slow. It takes slightly more than the frame rate of 1/30 seconds, but I’m going to try using threads to have it run over the course of several frames instead of freezing the game until it finishes.

There’s almost certainly a more efficient way to run the pathfinding algorithm, but I’d rather figure out how to run script independent of the game’s physics.

Siphons | 2019-02-12 18:11