0 votes

Hello-

I have a turn based game. On the AI's turn, I run a "for loop", which goes through each of the enemy units, and then determines what action that enemy should do (e.g. move, attack, defend). There may be like 100-150 enemies max.

While it's the AI's turn, I am trying to move the Camera2d around the map (basically using physics_process to check for arrow key inputs, then updating the the Camera2d's offset).

The Camera2d movement is sporadic and choppy at best. My guess is that the AI's "for loop" is consuming so much resources that the Camera2d's physics_process can't update real-time, and so there is a big lag.

When it's the Human's turn, the Camera2d's movement works perfectly.

I added a yield(create-timer for like 0.01 seconds) in the AI "for loop", but that didn't help.

Any suggestions on how to limit how much "processing power" the AI gets during their turn?

Open to any ideas, even out of the box...

Godot version v3.4.4.stable
in Engine by (176 points)

1 Answer

+1 vote
Best answer

You need to use threads (https://docs.godotengine.org/en/stable/tutorials/performance/threads/using_multiple_threads.html). Most of the engines lifecycles can be split into next major segments:
1. Handle user input.
2. Process all methods.
3. Render frame.
So until all methods are processed, frame will not be drawn. In other words, until your "for" loop is not finished, image on screen will not be updated. This is why you experience freezes on enemy's turn. Threads allow you to move your code from main thread to separate, making it possible to update frames before for loop is finished.
Note that not all operations are thread-safe (https://docs.godotengine.org/en/stable/tutorials/performance/threads/thread_safe_apis.html).

by (1,466 points)
selected by

Thank you for putting me in the right direction. I'll look into what AI method's I can optimize by putting on a thread(s)

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 Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.