This is the first day of my participation in the Gwen Challenge in November. Check out the details: the last Gwen Challenge in 2021
Cocos Creator front and background switching event monitoring code is as follows
onLoad: function () { cc.game.on(cc.game.EVENT_HIDE, this.onHide, this); cc.game.on(cc.game.EVENT_SHOW, this.onShow, this); }, onHide() {console.log(" game goes into background "); } onShow() {console.log(" game in foreground "); }Copy the code
After the program switches to the background, the entire rendering and event cycle is suspended, and some event logic that needs to be processed normally in the background is either moved to the server side for processing, or a timer is started in the background for processing.
The update function and the schedule timer are disabled after switching to the background, but setTimeout and setInterval work normally.
setTimeout
What it does: Sets a timer that triggers after the specified time (milliseconds) to call the incoming callback function.
Parameter types :(function/code, delayTime, args…)
- Function: callback function
- Code: string code that will be used
eval()
Execute, so it is not recommended- DelayTime: (optional) delayTime (milliseconds). The default value is 0.
- Args: (optional) an indefinite list of arguments that are passed to the callback function
setInterval
What it does: Sets a timer that triggers every once in a while to call the incoming callback function.
Parameter types :(function/code, delayTime, args…) This is the same as setTimeout, except that setInterval always executes the callback function, but setTimeout executes only once. DelayTime is the time of each interval.
We can use the setInterval timer to achieve the update effect.
public m_timer; OnHide () {console.log(" game goes into background "); // Let dt = 1/ cc.game.getFramerate (); // This. M_timer = setInterval(this. Update, dt*1000, dt); } onShow() {console.log(" game in foreground "); // Delete timer clearInterval(this.m_timer); }Copy the code
One minor issue is that the dt interval for the update function is not fixed at 1/ frame rate (similar to the difference between update and fixedUpdate).
At present, I have not come up with a good solution. For my current project, I have come up with two methods to provide you with some ideas:
-
Replace the Update with a timer at a fixed interval, so that the front and back transitions are not affected.
-
Appropriately increase the time interval of the timer when the background runs (slightly slower than the Update run by the foreground, because if the background runs faster than the foreground, the project display will have bugs), and perform a unified synchronization when cutting back to the foreground.