My next Phaser example was planned to be about sprite collision, I realized I had a growing number of examples and it would be nice if the blog post about the example could link directly to the example. This sort of deep linking is a part of frameworks such as Angular.

While this would probably not be too useful for a game it is useful for this type of project where each scene is unique enough to want to be able to link directly to a scene within the Phaser project.

In menu scene create:

let urlParts = window.location.href.split('#');
if (urlParts[1] && urlParts[1].length > 0) {
   this.loadSceneFromUrl(urlParts[1])
}

Now the menu scene is sort acting like a router. If a hash argument is provided and it matches one of the scenes it will be loaded.

loadSceneFromUrl:

loadSceneFromUrl(part: string) {
	this.items.forEach((item:{ text: string, scene: string, description: string }) => {
		if (item.scene.toLowerCase() === part.toLowerCase()) {
			this.textDescription.innerHTML = item.description;
			this.scene.start(item.scene);
		}
	});
}

I also added a description to the menu items to display some text below the examples with a link to the blog post associated with the example.

I have never thought about needing deep linking in a Phaser app. In this style of app, it is quite useful.

Screen shot of visual studio code phaser 3 menu scene

Github -> MenuScene.ts

This allows for linking directly to a scene https://mobsor.com/phaser-3-examples/#BulletsScene and also allows the user to refresh the page and reload the current scene instead of going back to the menu.

Todo: While refresh and linking work the back button does not. If I click on a menu item I would expect the back button to return to the menu. Some more research is needed on working with the browser history and deep linking.

Leave a comment

Your email address will not be published. Required fields are marked *