Save the game and let the game continue to play in background

Hi,

I make a game with babylon js and socket io and i have an issue. I don’t have any idea to how let the browser play the game when it’s in background and to load a save of the scene when browser reloading.

Hey there,

Good questions. Let’s start from the bottom, loading a save of the scene when the browser reloads. A common way is to store the state like entity positions for example in a database. You can than retrieve those from your server, each time the user reloads the browser they can do an http request to the web server which in turn grabs from the DB.

For faster access you can also store your state locally in the localstorage for example. Then you have to manage the state.

About running in background there are two concepts of background when dealing with browsers, the first is when the whole browser is in the background and the second is when the games tab is not active. You can activate background rendering for babylonjs with the renderEvenInBackground property. For example : engine.renderEvenInBackground = true . This will make sure your scene renders when the window is in the background.

Now for the use case when the tab is not active it’s a different story. Browsers like google chrome for example try to render as little as possible in the tabs which are not active, and for good reasons. This means that the core function which makes the animations possible, requestAnimationFrame is not executed in the tabs which are not active. Babylonjs renders using that function so the function will not be called thus the scene won’t be rendered.

You can also run everything under settimeout, which, as far as I’m aware is called, however I don’t remember getting good results when trying it.

I hope you find this helpful!

1 Like

Thank for your help. This seems to be complicated to set up for my project as it’s finished soon. Next time i’ll set up that at the beginning of the project.

Anyway thanks for this ideas, that’s helpfull.

1 Like