What is the best way to keep track of NPCs (Kinematicbody2D) position after changing the scene?

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

I want to create a town, where NPCs (Kinematicbody2D) have a fixed schedule. I gave them a signal, once they reach a certain “in-game tick”, they will walk (move_and_collide) to a specific position and perform an action (animation).
The player is not fixed to the town and can switch between maps (scenes). When I switch back to the town scene, I set the position of the NPCs according to the time I entered the scene.
The method works, but not so smoothly. For example, if I leave the town right before the next schedule and switch the scene back immediately, the NPCs will teleport to their new position instead of walking there.
So, is there a way to keep track of NPCs’ position, even when the scene is changed or queued?

:bust_in_silhouette: Reply From: IceExplosive

Once you swap a scene (so you are deleting the old one).
Everything in that scene is lost and deleted.

You have to use some way of storing that information somewhere else.

Should you need really persistent system, then you can go with some light database like SQLite or similar, I’m sure there are tutorials for it in Godot as well.

Another option is purely in-memory.
You can for ex. have extra scene (It can be singleton) that will serve as storage.

So… when you are leaving a city (deleting it’s scene)
you’ll save all required info into that singleton in some structure like array or something, which will be stored under the Name or Id of that city.

When you are loading a city that the first thing you do (after initialization) is to look into that singleton → are there data for this city?

If yes → you will change positions based on that…

But, this will actually solve half of your problem only.
Because in this way, you will move NPC into positions in which you left them (like they were frozen).
So you’ll have to add another step and that is to compute based on the time the exact positon.

Into singleton you can also save timestamp at which you’ve left that city and after entering, you’ll compute delta time (current_time - stored_time) and move NPC based on that delta.

Something like this might work, but I’d really think about if it’s that needed.
If player is expected to move from one city to another only occasionally… it’s not worth it.

And even if they would notice → “hey! they’ve just skipped half of their route!” it does not really change the gameplay and it might look little silly, but noone will care much.