+1 vote

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!

asked Feb 12, 2019 in Engine by Siphons (13 points)

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

https://docs.godotengine.org/en/latest/classes/class_thread.html?highlight=thread

Multithreading will not always be simple though.

If the process can be split into multiple units then there's also the "yield" function:
https://docs.godotengine.org/en/latest/classes/class_@gdscript.html?highlight=yield#class-gdscript-method-yield

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.

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.

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.

Please log in or register to answer this question.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.