phaser world issue 119 · a cute time killer game template with full source, easy to reskin and...

41
Welcome to Issue 119 of Phaser World Hello! It's been a couple of weeks since issue 118 because we've been utterly snowed-under with work on Phaser. You can read all about that in this issues

Upload: others

Post on 09-Mar-2020

5 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Phaser World Issue 119 · A cute time killer game template with full source, easy to reskin and export to mobile. How to Create a Game with Phaser 3 A comprehensive new tutorial from

Welcome to Issue 119 of Phaser World

Hello! It's been a couple of weeks since issue 118 because we've been utterlysnowed-under with work on Phaser. You can read all about that in this issues

Page 2: Phaser World Issue 119 · A cute time killer game template with full source, easy to reskin and export to mobile. How to Create a Game with Phaser 3 A comprehensive new tutorial from

Dev Log. This issue is a special double-length edition to make up for missing aweek, with a huge and exclusive tutorial on Phaser 3 Scenes, news on the docs,TypeScript, a double-dose of articles and more!

Until the next issue, keep on coding. Drop me a line if you've got any news you'dlike featured by simply replying to this email, messaging me on Slack, Discord orTwitter.

The Latest Games

Game of the Week Exocraft Design unique exocraft and build your fleet of drones to battle and mine forresources in this massively multiplayer action strategy set in an alien wasteland.

Staff Pick Breaking Bricks It's breakout in overdrive! Up to 4 local players, 13 boss battles, 198 levels,gamepad support and superb graphics and sound.

Page 3: Phaser World Issue 119 · A cute time killer game template with full source, easy to reskin and export to mobile. How to Create a Game with Phaser 3 A comprehensive new tutorial from

Wedding Run Creating to celebrate a wedding this is a fun platformer. Collect the coins andavoid the bunnies! Source code also available.

BeFive Dealer Ginjirou A classic betting game given a nice visual twist. Bet your (virtual) credits on anodd or even outcome and win big, or go home shirtless.

Whippy Chute A cute little free Android game, just tap to change the direction of your chute.

What's New?

Phaser 3.3.0 Released

Page 4: Phaser World Issue 119 · A cute time killer game template with full source, easy to reskin and export to mobile. How to Create a Game with Phaser 3 A comprehensive new tutorial from

The latest update to Phaser 3 is out and contains no less than 100enhancements across the API. From new camera effects to bug fixes,development continues at a rapid pace.

Phaser CE v2.10.3 Released This new point release fixes an issue with Cocoon packaging of Phaser games.

Ethercraft Trading, Crafting, and Dungeon Crawling on the blockchain. A decentralized RPGrunning on the Ethereum Blockchain.

Dungeon Escape A cute time killer game template with full source, easy to reskin and export tomobile.

How to Create a Game with Phaser 3 A comprehensive new tutorial from Game Dev Academy, with full source andassets included.

Page 5: Phaser World Issue 119 · A cute time killer game template with full source, easy to reskin and export to mobile. How to Create a Game with Phaser 3 A comprehensive new tutorial from

Pathfinding and Phaser 3 An A to Z guide to pathfinding with Easystar and Phaser 3.

TexturePacker and Phaser 3 Tutorial A tutorial with examples on how to create sprite sheets for Phaser 3 withTexturePacker.

Game Distribution API Tutorial A guide on integrating your game with the Game Distribution API to takeadvantage of their services.

Thank you to our awesome new Phaser Patrons who joined us this week:

rex colbydude Melissa Sorrells

also thank you to Paul for the donation.

We are currently 94% of our way to the next funding goal: "We will publish an

Page 6: Phaser World Issue 119 · A cute time killer game template with full source, easy to reskin and export to mobile. How to Create a Game with Phaser 3 A comprehensive new tutorial from

exclusive Phaser 3 code example once per month. Patrons get to vote on thetopic they'd like to see covered in the example."

Patreon is a way to contribute towards the Phaser project on a monthly basis.This money is used entirely to fund development costs and is the only reasonwe're able to invest so much time into our work. You can also donate via PayPal.

Backers get forum badges, discounts on plugins and books, and are entitled tofree monthly coding support via Slack or Skype.

Dev Log #119It's been a couple of weeks since the last Dev Log and the reason for this is thatso much has been happening that I really struggled to find the time to write. Ittakes a lot of effort, many hours of work, to create the newsletter each week. Ipersonally write all the articles on the site. I grab the screenshots, play thegames, source the links and put it all together. Then I write the Dev Logs as well.In a typical week, it takes around 1.5 days to do all of these tasks, which is timeI've been spending working on Phaser instead. I've tried getting people to help inthe past, but even when offering to pay them they rarely last more than a fewweeks and then I'm back to doing it on my own.

However, I know it's the main way in which you all read about what is happening,so I'll try to make sure we get back to being weekly again soon. I guess a littlenews often, is better than large dumps of news more sporadically.

And a heck of a lot has been happening. Massive amounts of work on the APIDocs, TypeScript defs, the 3.3 release and all the work put into the 3.4 release

Page 7: Phaser World Issue 119 · A cute time killer game template with full source, easy to reskin and export to mobile. How to Create a Game with Phaser 3 A comprehensive new tutorial from

being worked on at the moment. Plus we've Containers up and running too. Soit's safe to say that if we skip a week for the newsletter it's literally only becausePhaser itself is being advanced at such a rate.

Thank you to everyone who supports Phaser. We're nearly at the end of thefunding received from Mozilla, so every little bit we get from Patreon anddonations helps right now. If you can't contribute financially then please perhapshelp with finding bugs, helping with the docs or just spreading the word aboutPhaser to your peers. It all helps :)

API Docs and TypeScript Defs

I've spent many days over the past couple of weeks working on the v3documentation. This has entailed fixing no less than 1034 data-types, creatingtypedefs, refactoring the way certain classes export and endlessly testing, andre-testing the jsdoc export. It's a truly tireless task.

Progress has been great though and a couple of really good things have comeout of this effort. First, I published the Phaser 3.3 API docs and they're nowhosted on GitHub Pages, so you can browse them online:

Phaser 3 API Documentation

This is using the foodoc template, which isn't perfect but is much better than thealternatives. The downside is it takes just over 1 hour to generate the html, whichis highly frustrating. I'm working hard on our own SQL based template, so youcan do proper searches and cross-indexes and that will be presented on our website. For now, though, the GitHub version is better than nothing. And at least all ofthe returns and data-types are accurate.

My thanks to community member orblazer for helping with so much of this work.As a result of our combined effort, Peter was finally able to complete hisTypeScript Definitions generator. It took a lot of trial and error but we're nowgenerating fully-compiling TypeScript defs direct from the Phaser source code.

You can download the TypeScript Definitions here.

This is our first pass at the defs. There are improvements to be had, but at leastyou can download them and use them in your projects. We will not be addingthem in to our @typings package until they are more robust.

We have also published the source code to our TS Defs Generator (which itselfis written in TypeScript) and you can find it, along with tests in the Phaser 3 Docs

Page 8: Phaser World Issue 119 · A cute time killer game template with full source, easy to reskin and export to mobile. How to Create a Game with Phaser 3 A comprehensive new tutorial from

repo. See the README for more details.

If you would like to help refine the TS defs, or docs, then please do. I often getasked by people "when will the docs be ready?" but the truth of the matter is that,as of today, there are still over 7000 items in the API that need documenting. Ifyou search the v3 source for the string '[description]', that is the tag we use toindicate that docs need to be written for that item. It may be a property, or amethod, or a return statement or a function, but if it has that tag it means we'vecompleted the data-type for it, but not the explanation as to what it is or does.Some are more obvious than others - if you come across one that you feel youcould accurately describe then we would love a pull request from you to add it.

So, when will the docs be 100% complete? I don't really know. If we worktogether then perhaps quite soon. If I have to do them all on my own, then it'sgoing to take several months at least. In the meantime, please stop asking, I'mafraid there is no magical docs fairy to write them for us, it's going to take hardwork and nothing less.

Phaser 3.3 Release

Phaser 3.3.0 was released on March 20th and represented 10 days worth ofdevelopment since the previous version. I'm sure you'll agree the Change Log ispretty epic given the quite short amount of time.

There are 32 new features in 3.3.0 and here are some of the highlights:

▪ Lotsof

Page 9: Phaser World Issue 119 · A cute time killer game template with full source, easy to reskin and export to mobile. How to Create a Game with Phaser 3 A comprehensive new tutorial from

newGameConfigurationpropertieswhicharepassedtotherenderer,includingpowerpreferences,anti-aliasing,drawingbufferpreservationandmore.

▪ ArcadePhysicscannowwrapphysicsbodiesaroundtheworld.

▪ Camerashake,fadeandflashallnowhaveoptionalcallbacksthatcanbeinvokedwhenthe

Page 10: Phaser World Issue 119 · A cute time killer game template with full source, easy to reskin and export to mobile. How to Create a Game with Phaser 3 A comprehensive new tutorial from

effectcompletes.

▪ CamerafadeInandCamerafadeOutaretwonewmethodstohelpwithscenetransitions(alsowithcallbacks)

▪ GroupsnowlistenforthedestroyeventcomingfromchildrenandautomaticallypurgethemfromtheGroupifreceived.

▪ ThereisanewMatterGameObjectwhichallowsyou

Page 11: Phaser World Issue 119 · A cute time killer game template with full source, easy to reskin and export to mobile. How to Create a Game with Phaser 3 A comprehensive new tutorial from

tobindaMatterPhysicsbodywithanyrenderableGameObject,suchasText,BitmapTextorTileSprite(seethelabsforexamples)

▪ TheSoundManagerhasnewchainablesetRateandsetDetunemethods.

Remember, these are just the new features. There are also 21 bug fixes and 47updates. Lots of those updates introduce new features too but in a non-invasive(to the API) way.

Containers

Felipe has been working on implementing Containers into the core API. Theseare their own special kind of Game Object that can support having children.Modify the container and the children are all updated immediately. A lot of efforthas been spent ensuring that the process of merely adding containers into theAPI didn't adversely affect anything else. For those of you who don't need to use

Page 12: Phaser World Issue 119 · A cute time killer game template with full source, easy to reskin and export to mobile. How to Create a Game with Phaser 3 A comprehensive new tutorial from

them, we were adamant that you shouldn't have to pay any processing cost formaking that choice. Only those who actively create containers will get theoverhead required to process them added to their games. This took quite a bit ofresearch. However, we're now happy they are working and rendering correctlyas you can see in the demo below.

Containers support any type of rendering Game Object as a child, including otherContainers. If the Container is on the root display list (i.e. not nested withinanother) then you can apply a Bitmap Mask to it and it'll mask the Container andall its children.

If you would like to experiment with Containers you can checkout the containersbranch of the Phaser repo. Once Phaser 3.4 is released we will merge thisbranch into master ready for version 3.5, which is estimated to be a couple ofweeks away.

A Guide to ScenesI've seen a lot of people asking about Scenes. What they are, how to use themand how to get two scenes to talk together. In this tutorial, I'm going to cover all ofthese topics. This tutorial will also be published to the Phaser website, but for

Page 13: Phaser World Issue 119 · A cute time killer game template with full source, easy to reskin and export to mobile. How to Create a Game with Phaser 3 A comprehensive new tutorial from

now, newsletter readers get it exclusively. There's a lot of information coming up,so get comfy and settle in.

What is a Scene?

In Phaser 2 there was the concept of a Game World and States. A State allowedyou a view into the Game World and only one State could ever be running atonce. The State had access to all kinds of systems, such as a Camera, Tweensand the Game Object Factory. When you used a command like `this.add` fromwithin a State, you were talking to the global Game Object Factory. Once youwere done with a State you moved to the next one. States were often split up intological sections, such as a Preloader State, a Main Menu State and so on.

In Phaser 3 we changed our approach to this entirely. The first change was thatStates were renamed to Scenes. This was to avoid ambiguity with 'statemachines', which are commonly used in games. The global State Manager wasalso replaced with a Scene Manager. The changes were not just in the naming ofthe classes though, they run much deeper than this.

Rather than Phaser managing one 'Game World' there is now no World object atall. Instead of Scenes just having references to all of the systems that thePhaser.Game instance owns, they now own them themselves. You can think ofScenes as being almost entirely self-contained Game Worlds in their own right.They manage their own input, tweens, game objects, display list, cameras andmore. A Tween created in Scene A is completely separate to one created inScene B.

Scenes now control everything using their own instances of plugins. In fact, theonly thing that the Game itself is responsible for is passing on global DOM-basedevents to the Scenes, such as when to update (from RequestAnimationFrame)or core input events from the Input Manager. The handling of these events isdone by the Scenes themselves though.

What does Game still control?

There are a few systems which are inherently global in their nature and thereforebelong to the Game instance. These are:

▪ TheRenderer.Thereisonly

Page 14: Phaser World Issue 119 · A cute time killer game template with full source, easy to reskin and export to mobile. How to Create a Game with Phaser 3 A comprehensive new tutorial from

oneinstanceofeithertheCanvasorWebGLRendererperGame,andit'sapropertyoftheGameobject.

▪ TheAnimationManager.AnimationsinPhaser3areglobalandnolongerboundtoaspecificGameObject.Youcancreatemanydifferentanimations,whichareall

Page 15: Phaser World Issue 119 · A cute time killer game template with full source, easy to reskin and export to mobile. How to Create a Game with Phaser 3 A comprehensive new tutorial from

storedintheAnimationManager,andthenanyGameObject,inanyScene,canusethemwithoutduplicatinglotsofdataandwastingmemory.

▪ TheCache.WhenfilesareloadedbyaScenetheyareplacedintoaglobalcache.SoifSceneAloadsan

Page 16: Phaser World Issue 119 · A cute time killer game template with full source, easy to reskin and export to mobile. How to Create a Game with Phaser 3 A comprehensive new tutorial from

XMLfile,thatXMLdatacanberetrievedbyanySceneasthecacheisglobal.

▪ TheRegistry.EveryScenehasitsowninstanceoftheDataManager,buttheGamealsohasonewhichyoucanreferencefromaSceneviatheproperty`registry`.Thisallows

Page 17: Phaser World Issue 119 · A cute time killer game template with full source, easy to reskin and export to mobile. How to Create a Game with Phaser 3 A comprehensive new tutorial from

foreasycross-Scenedataexchange(aswe'llseelaterinthisguide)

▪ TheInputManager.TheInputManagerdoesverylittleinPhaser3.ItjustmonitorsandprocessesDOM-levelinputevents,suchasthoseraisedfrompointers,gamepadsorthekeyboard.EveryScene

Page 18: Phaser World Issue 119 · A cute time killer game template with full source, easy to reskin and export to mobile. How to Create a Game with Phaser 3 A comprehensive new tutorial from

hasitsownInputPlugin,whichiswhatdoesalloftherealworkwiththeevents,andiswhatyouinterfacewithwhencalling`this.input`fromaScene.

▪ TheSceneManager.Responsibleforcreating,managingandupdatingalloftheScenesinyourgame.

▪ The

Page 19: Phaser World Issue 119 · A cute time killer game template with full source, easy to reskin and export to mobile. How to Create a Game with Phaser 3 A comprehensive new tutorial from

DeviceInspector.Allowsyoutopollforfeaturessupportedbythebrowserandhardwareyourgameisrunningon.TheDeviceclassisactualasingletonandonlyrunsonceperbrowser,soisn'tdirectlyboundtoyourGameinstance(i.e.ifyouhad2game

Page 20: Phaser World Issue 119 · A cute time killer game template with full source, easy to reskin and export to mobile. How to Create a Game with Phaser 3 A comprehensive new tutorial from

instancesrunningonthesamepage,theywouldsharetheglobalDeviceinspector)

▪ TheSoundManager.Likerendering,soundsaremanagedbyaglobalsysteminPhaser3.YoucancreateSoundobjects,markers,andsoonfromyourScenes,butthereisonlyonemanager

Page 21: Phaser World Issue 119 · A cute time killer game template with full source, easy to reskin and export to mobile. How to Create a Game with Phaser 3 A comprehensive new tutorial from

runningatoncetoavoidresourceallocationissues.

▪ TheTimeStep.ThispluginmanagestheRequestAnimationFrameloopandupdatesthecoreGame,causingittostep.Yourarelyneedtointeractwiththisdirectly.

Everything else, such as Tweens, Physics, Game Objects and Input handlingare all managed through Scene level plugins. The Game is now only used for thetimestep and the systems that are truly global, which wouldn't have made senseto duplicate per Scene.

What happens when you create a Scene

There are lots of different ways to create a Scene but the fundamental approachis the same in all of them. A Scene consists of a Scene Configuration object and

Page 22: Phaser World Issue 119 · A cute time killer game template with full source, easy to reskin and export to mobile. How to Create a Game with Phaser 3 A comprehensive new tutorial from

a bunch of functions. Here we'll create an example Scene using an ES6approach:

We extend the `Phaser.Scene` object and give it a unique key (in this case`MyFirstScene`) in the constructor. There are two methods: `preload` and`create`. The first loads an image, the second displays it. You don't have to havea `preload` method, the only requirement to be a valid Scene is a `create` methodas this is the global entry-point of all Scenes in Phaser 3.

Here is the exact same thing using ES5:

Creating the Scene on its own isn't enough though, it also needs to be added to

Page 23: Phaser World Issue 119 · A cute time killer game template with full source, easy to reskin and export to mobile. How to Create a Game with Phaser 3 A comprehensive new tutorial from

the Game. You can do this when the Game is created, using the game config likethis:

The Scene has been passed in via the `scene` property. This can also be anarray of Scenes if you have more than one. This is exactly the same regardlessof ES5 or ES6.

If you've looked at any of the Phaser 3 examples you'll probably have seen acompletely different method of creating a Scene that looks more like this:

So hang on a minute, in the ES6 and ES5 Scenes we passed an instance ofthem in the game config, but in the above code we're passing an actual object

Page 24: Phaser World Issue 119 · A cute time killer game template with full source, easy to reskin and export to mobile. How to Create a Game with Phaser 3 A comprehensive new tutorial from

with just a couple of properties (`preload` and `create`) instead.

The reason this works is that, internally, the Scene Manager does a lot todetermine what's being given to it.

First it looks at the `scene` property of the game config. If it's an array it theniterates through it, processing each entry in turn, otherwise it just processes thefirst entry found. It inspects each item given to it to see what type it is, i.e. aclass, an object or a prototype function, and then turns them into full Sceneobjects, adding them into the Scene Manager.

Ultimately, it doesn't matter which approach you use to define your Scene, oncethe Scene Manager is done with them they're all treated the same internallyanyway. And it's when they get turned into full Scenes that they gain severalimportant additions such as the Scene Settings and Systems, plus the ability tocommunicate with each other.

Scene Settings

When your Scene is created it extracts any settings you may have defined in itsconfig. If there aren't any, it just uses the defaults. Settings are defined in aconfiguration object passed to the Scene constructor. Here's an example ofsetting the Scenes name and physics engine from the config:

The Settings object can also be used to load files. You should really only use this

Page 25: Phaser World Issue 119 · A cute time killer game template with full source, easy to reskin and export to mobile. How to Create a Game with Phaser 3 A comprehensive new tutorial from

for loading small files as no progress feedback is ever given to the user. Use thefollowing syntax:

The assets are loaded before your Scene Preload method is called.

It's perfect for loading a very small number of graphics, i.e. a background andprogress bar image, that your Preloader Scene can then display while loading allthe rest of the game assets. Or you could use it to load your internal game config,which could be parsed before loading the rest of the assets.

Scene Systems

When the Scene Manager creates your scene it installs a Scene Systems objectinto it. This is placed on the property `sys`, meaning you should never replace oroverwrite the property `sys` in your game code, or very bad things will happen :)

The Scene Systems class is the heart of your Scene. It controls all of the Sceneplugins, emits events, lets you to modify the Scene (such as sending it to sleep,waking it up, etc) and allows all of the plugins to communicate with the eachother.

It will automatically install 7 Core Plugins into your Scenes:

▪ AnEventEmitter

▪ The2DCamera

Page 26: Phaser World Issue 119 · A cute time killer game template with full source, easy to reskin and export to mobile. How to Create a Game with Phaser 3 A comprehensive new tutorial from

Manager▪ The

GameObjectCreator

▪ TheGameObjectFactory

▪ TheScenePlugin

▪ TheDisplayList

▪ TheUpdateList

As you can see from the list above, each Scene has its own Display List,factories and Camera system. So when you issue a command like`this.add.image` you're interfacing directly with the Scene based Game ObjectFactory, and adding the resulting image to the Scene level display list.

These plugins are non-optional, as they all rely on each other being present. Soevery Scene has them. However, you can control which are exposed asproperties on the Scene objects via the Injection Map.

There are also 7 Default Plugins. These are installed into your Scenes unlessyou specify otherwise via the Scene config:

▪ The3DCameraManager

▪ TheClock

▪ TheDataManagerPlugin

▪ TheInputPlugin

Page 27: Phaser World Issue 119 · A cute time killer game template with full source, easy to reskin and export to mobile. How to Create a Game with Phaser 3 A comprehensive new tutorial from

▪ TheLoaderPlugin

▪ TheTweenManager

▪ TheLightsPlugin

The plugins above are all optional. As with the Core Plugins you can controlwhich ones are exposed via properties using the Injection Map.

Configuring Plugins

Remember that the Core Plugins cannot be removed. To remove all of theDefault Plugins you simply have to pass an empty plugins array in your sceneconfig:

If you now try and use `this.load` in your Scene, it will fail, because the LoaderPlugin has been excluded from this Scene.

If you want just the Loader and Tween plugin, but none of the others, you canspecify just those:

Page 28: Phaser World Issue 119 · A cute time killer game template with full source, easy to reskin and export to mobile. How to Create a Game with Phaser 3 A comprehensive new tutorial from

If you're not sure which plugins you will need when you create your Scene youcan install them via the Scene Systems. This must be done in an `init` method:

The call to `install` tells it to install the Default Plugin `TweenManager`, allowingyou to add tweens in this Scene.

Scene Injection Map

In Phaser 2 the State Manager would create no less than 19 properties withinyour State, all linked to global game systems. For example, it would take yourState and then add the `physics` property to it, which mapped to the Physicsmanager, `scale` mapped to the Scale Manager, and so on.

Page 29: Phaser World Issue 119 · A cute time killer game template with full source, easy to reskin and export to mobile. How to Create a Game with Phaser 3 A comprehensive new tutorial from

This was a double-edged sword. It made Phaser incredibly easy to use. Therewas no convoluted access required to a system, you literally just typed it out andthere it was. However, you had no choice over the quantity or name of theproperties that were injected. If you really wanted to use a local property called`world` you couldn't without literally breaking your game. If you accidentallyoverwrote one of the 19 default properties, it would also break your game.Experienced devs learned to deal with this but we thought there was a better wayfor Phaser 3.

To that end, we created a Scene Injection Map. This object controls whichplugins are mapped to properties within your Scene, and controls exactly whatthose properties are called.

By default all of the following properties are installed into a Scene:

'anims' = Animation Manager (Global) 'cache' = Cache (Global) 'game' = Phaser.Game instance (Global) 'registry' = Game Data Manager (Global) 'sound' = Sound Manager (Global) 'textures' = Texture Manager (Global)

'add' = Game Object Factory (Local, Core) 'cameras' = 2D Camera Manager (Local, Core) 'children' = Display List (Local, Core) 'events' = Event Emitter (Local, Core) 'make' = Game Object Creator (Local, Core) 'scene' = Scene Manager Plugin (Local, Core)

The following properties are installed into a Scene only if the respective plugin isavailable:

'cameras3d' = 3D Camera Manager (Local, Optional) 'data' = Scene Data Manager (Local, Optional) 'impact' = Impact Physics (Local, Optional) 'input' = Input Plugin (Local, Optional) 'lights' = Lights Manager Plugin (Local, Optional) 'load' = Loader Plugin (Local, Optional) 'matter' = Matter JS Physics (Local, Optional) 'physics' = Arcade Physics (Local, Optional) 'time' = Time / Clock Plugin (Local, Optional) 'tweens' = Tween Manager (Local, Optional)

Page 30: Phaser World Issue 119 · A cute time killer game template with full source, easy to reskin and export to mobile. How to Create a Game with Phaser 3 A comprehensive new tutorial from

If you prefer you can choose not to have any properties added to your Scene atall:

Or you can change the name of the property that is injected using the `map`object. Here we will replace the English properties with Spanish equivalents:

Page 31: Phaser World Issue 119 · A cute time killer game template with full source, easy to reskin and export to mobile. How to Create a Game with Phaser 3 A comprehensive new tutorial from

If your IDE supports it, you can even use UTF8, such as this Simplified Chineseversion:

Page 32: Phaser World Issue 119 · A cute time killer game template with full source, easy to reskin and export to mobile. How to Create a Game with Phaser 3 A comprehensive new tutorial from

Cross Talk - Calling a Scene function

Now we know how to create and configure Scenes, let's get them talking to eachother. There are several ways to achieve this: Calling a function directly, listeningfor an event or exchanging data via the registry. We'll cover each now:

Calling a Scene Function

First, we'll create two basic Scenes:

Page 33: Phaser World Issue 119 · A cute time killer game template with full source, easy to reskin and export to mobile. How to Create a Game with Phaser 3 A comprehensive new tutorial from

Here SceneA listens out for pointer events. When it receives one it calls the`clickHandler` method. In here we grab a reference to SceneB. This is doneusing the Scenes key, which is `MySecondScene`. Once we have that, we cancall any public methods which it exposes. In this case we're calling `getPosition`.This method returns a vec2 with a random location in it. We then add an image atthat location.

It's not exactly a complex example, but you should get the idea: Any publicfunction defined on a Scene can be called by any other scene.

Page 34: Phaser World Issue 119 · A cute time killer game template with full source, easy to reskin and export to mobile. How to Create a Game with Phaser 3 A comprehensive new tutorial from

Listening for Scene Events

In this example instead of calling a function on SceneB directly, we're going tohave it listen for events from SceneA. The set-up is the same as before, but ourclickHandler is different:

Page 35: Phaser World Issue 119 · A cute time killer game template with full source, easy to reskin and export to mobile. How to Create a Game with Phaser 3 A comprehensive new tutorial from

Here, when a box is clicked, we dispatch the `addScore` event. Our SceneBlooks like this:

Page 36: Phaser World Issue 119 · A cute time killer game template with full source, easy to reskin and export to mobile. How to Create a Game with Phaser 3 A comprehensive new tutorial from

It creates a text object to display the score, gets a reference to SceneA and thenlistens for `addScore` events from it. When it receives one it updates the localscore and Text object.

The advantage to this approach is that SceneA is not tightly coupled to yourSceneB. As long as the event names don't change, SceneA can happily sit there,dispatching events as long as it likes, knowing that any other Scenes interestedin them will pick them up. However, it does mean that SceneB is coupled toSceneA, as it needs a reference to it in order to listen to its event emitter. We canavoid this entirely by using the Game Registry.

Page 37: Phaser World Issue 119 · A cute time killer game template with full source, easy to reskin and export to mobile. How to Create a Game with Phaser 3 A comprehensive new tutorial from

Exchange Data via the Game Registry

We're going to expand upon the previous example slightly. This time we will beusing the Game Registry, which is an instance of the Data Manager Plugin, inorder to exchange data. This is SceneA, our GameScene. It's the same asbefore, except we tint every other box red. If you click a red box then you loseone of your lives. If you click a normal box, you gain a point:

Page 38: Phaser World Issue 119 · A cute time killer game template with full source, easy to reskin and export to mobile. How to Create a Game with Phaser 3 A comprehensive new tutorial from

As the boxes are clicked we updated the respective values in the registry usingthe `registry.set` call.

Now to SceneB. This Scene is the same as before, except we've added anotherText object to display the lives remaining:

Page 39: Phaser World Issue 119 · A cute time killer game template with full source, easy to reskin and export to mobile. How to Create a Game with Phaser 3 A comprehensive new tutorial from

It listens out for a `changedata` event from the Registry and invokes the`updateData` method if it receives one. This method is set 3 items: the parent, i.e.the owner of the Data Manager, which in this case is the Game. It then receivesthe string-based key of the entry that was changed, and then finally the new valueof this entry.

Page 40: Phaser World Issue 119 · A cute time killer game template with full source, easy to reskin and export to mobile. How to Create a Game with Phaser 3 A comprehensive new tutorial from

By checking the key we can tell if it was the score or the lives that were changedand update our text objects respectively.

As you can see, using the Game Registry gives us a fully decoupled method ofcommunication between multiple Scenes.

In the next tutorial we will look at the visual aspects of Scenes - changing theirposition on the scenes list, and how to make them sleep and wake.

This is a great article: Making computer games from scratch in 1987.

When iOS throttles Request Animation Frame to 30fps.

ElefantaSTic by the Genesis Project is a super-cute Atari ST demo, with lovelygraphics and music.