📜 ⬆️ ⬇️

HTML5 game pauses

Prehistory


Being in the process of developing my first html5 game, I ran into a number of difficulties, for most of them there are many ready-made solutions on the net, but I did not find a correct answer to the question: “How to pause the html5 game?” To all who this topic is interesting or necessary - I ask further ...

More about solutions


All the solutions I found on the Internet somehow operate on the principle of while.
Examples below:

Example 1

function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } async function demo() { console.log('Taking a break...'); await sleep(2000); console.log('Two second later'); } demo(); 

In this case, we set a pause for a while, after it has passed, the game continues ...
This solution will not work in most cases, if only because we do not know how long the user pauses, and also during the execution of the function, the user will not be able to interact with the menu.
')
Example 2

 function render(){ if(canRender == false){ requestAnimationFrame(render); }else{ //some code requestAnimationFrame(render); } 

Constant restarting and tracking of user actions, the memory is spent in empty.

My decision


So, highlighting the main problems found on the Internet solutions, I, putting it all together, got the following:

First, we will declare the object of rearing itself, the global position variable of the object and the variable for the pause, as well as an array, for which he will find out a little later.

 let sqrt=document.getElementById('sqrt'),rend=0,pause=false,functions=[]; 


Now let's declare the rendering function itself, which should be paused:

 function render(){ rend+=1.5; sqrt.style = 'bottom:' + rend +'vh'; if(rend<80){ requestAnimationFrame(render); }else{ rend=0; return; } } 

Next, we integrate the code for a pause into a function (in my example it is one, in your case there may be more functions)

 function render(){ if(pause!=false){ //        functions.push("render()"); //   return; } rend+=1.5; sqrt.style = 'bottom:' + rend +'vh'; if(rend<80){ requestAnimationFrame(render); }else{ rend=0; return; } } 

So, it’s small, add a function to handle pause / unpause

 function SetPause(){ if(pause==true){ UnPause(); }else{ pause=true; } } function UnPause(){ pause=false; //         for(i=0;i<functions.length;i++){ eval(functions[i]); } //     functions =[]; } 

Everything is ready, we received a mechanism that does not eat memory for nothing and gives the opportunity to interact with the page during a pause.

This article has been written for assistance. If anyone has seen such a decision before - I apologize. Thanks for attention!

Source: https://habr.com/ru/post/449466/


All Articles