Switching Scenes
Once your game reaches a certain size, you will want to start switching between scenes. That might be switching from a intro or menu to the game or from one level to another.
The most important function to know here is engine.scene.load(),
which will replace the current scene with a .bin
filename or URL you pass it for loading.
This could be an example of a component that switches to another scene after a certain amount of time:
1import {Component, Property} from '@wonderlandengine/api';
2
3export class LoadAfterDelay extends Component {
4 static TypeName = 'load-after-delay';
5 static Properties = {
6 sceneFile: Property.string("AnotherScene.bin"),
7 delaySeconds: Property.float(10),
8 };
9
10 start() {
11 setTimeout(() => {
12 this.engine.scene.load(this.sceneFile);
13 }, this.delaySeconds*1000);
14 }
15});
Preloading Scenes
While the scene will keep running while the next is loading, it will still cause a delay between when the load was initiated and the next scene appearing for the user.
To minimize this scene, you can put the following HTML tags into the <head>
or your
index.html
:
You can also add these tags dynamically via JavaScript.
Caveats
Loading a scene will not clear event listeners automatically. This includes
event listeners on DOM elements and callbacks added to emitters.
You are responsible for removing event listeners. It is best practice to
do this in onDeactivate
of your component.
onDeactivate
is called before onDestroy
. Both are called when a scene
is unloaded.
1 keyUpHandler = e => { /* ... */ };
2
3 onActivate() { /* or start() */
4 this.engine.canvas.addEventListener('keyup', this.keyUpHandler);
5 }
6
7 onDeactivate() {
8 /* Remove listener for scene reloads, otherwise keypress is
9 * handled multiple times or handled in the next scene also */
10 this.engine.canvas.removeEventListener('keyup', keyUpHandler);
11 }