phaser/README.md
2018-05-08 23:29:42 +01:00

32 KiB

Phaser - HTML5 Game Framework

Phaser Header

Phaser is a fast, free, and fun open source HTML5 game framework that offers WebGL and Canvas rendering across desktop and mobile web browsers. Games can be compiled to iOS, Android and native apps by using 3rd party tools. You can use JavaScript or TypeScript for development.

Phaser is available in two versions: Phaser 3 and Phaser CE - The Community Edition. Phaser CE is a community-lead continuation of the Phaser 2 codebase and is hosted on a separate repo. Phaser 3 is the next generation of Phaser.

Along with the fantastic open source community, Phaser is actively developed and maintained by Photon Storm. As a result of rapid support, and a developer friendly API, Phaser is currently one of the most starred game frameworks on GitHub.

Thousands of developers from indie and multi-national digital agencies, and universities worldwide use Phaser. You can take a look at their incredible games.

Visit: The Phaser website and follow on Twitter (#phaserjs)
Learn: API Docs, Support Forum and StackOverflow
Code: 700+ Examples (source available in this repo)
Read: Weekly Phaser World Newsletter
Chat: Slack and Discord
Extend: With Phaser Plugins
Be awesome: Support the future of Phaser

Grab the source and join the fun!

What's New

8th May 2018

I'm pleased to announce the immediate availability of Phaser 3.7.0. This release continues our mission of enhancing Phaser 3 as best and as quickly as we can. We've made significant improvements to the Loader Plugin, allowing for far more flexible file loading, new loader packs, new file formats, normal map support and more. We've also improved our build process, making Phaser 3 much easier to package outside of Webpack. You'll also find hundreds and hundreds of items now have full documentation too. As always, please check out the Change Log for comprehensive details about what recent versions contain.

About Phaser 3

After 1.5 years in the making, tens of thousands of lines of code, hundreds of examples and countless hours of relentless work: Phaser 3 is finally out. It has been a real labor of love and then some!

Please understand this is a bleeding-edge and brand new release. There are features we've had to leave out, areas of the documentation that need completing and so many cool new things we wanted to add. But we had to draw a line in the sand somewhere and 3.0.0 represents that.

For us this is just the start of a new chapter in Phaser's life. We will be jumping on bug reports as quickly as we can and releasing new versions rapidly. We've structured v3 in such a way that we can push out point releases as fast as needed.

We publish our Developer Logs in the weekly Phaser World newsletter. Subscribe to stay in touch and get all the latest news from us and the wider Phaser community.

You can also follow Phaser on Twitter and chat with fellow Phaser devs in our Slack and Discord channels.

Phaser 3 wouldn't have been possible without the fantastic support of the community and Patreon. Thank you to everyone who supports our work, who shares our belief in the future of HTML5 gaming, and Phaser's role in that.

Happy coding everyone!

Cheers,

Rich - @photonstorm

boogie

Support Phaser

Developing Phaser takes a lot of time, effort and money. There are monthly running costs as well as countless hours of development time, community support, and assistance resolving issues.

If you have found Phaser useful in your development life or have made income as a result of it please support our work via:

It all helps and genuinely contributes towards future development.

Extra special thanks to our top-tier sponsors: Orange Games and CrossInstall.

Sponsors

Weekly Newsletter

Every week we publish the Phaser World newsletter. It's packed full of the latest Phaser games, tutorials, videos, meet-ups, talks, and more. The newsletter also contains our weekly Development Progress updates which let you know about the new features we're working on.

Over 120 previous editions can be found on our Back Issues page.

Download Phaser

Phaser 3 is available via GitHub, npm and CDNs:

NPM

Install via npm:

npm install phaser

CDN

Phaser is on jsDelivr which is a "super-fast CDN for developers". Include the following in your html:

<script src="//cdn.jsdelivr.net/npm/phaser@3.7.0/dist/phaser.js"></script>

or the minified version:

<script src="//cdn.jsdelivr.net/npm/phaser@3.7.0/dist/phaser.min.js"></script>

API Documentation

  1. Go to https://photonstorm.github.io/phaser3-docs/index.html to read the docs online.
  2. Checkout the phaser3-docs repository and then read the documentation by pointing your browser to the local docs/ folder.

The documentation for Phaser 3 is an on-going project. Please help us by searching the Phaser code for any instance of the string [description] and then replacing it with some documentation.

TypeScript Definitions

TypeScript Definitions are now available.

They are automatically generated from the jsdoc comments in the Phaser source code. If you wish to help refine them then you must edit the Phaser jsdoc blocks directly. You can find more details, including the source to the conversion tool we wrote in the Docs repo.

As soon as we're happy with the accuracy of the TS defs we'll merge them into the main repo, for now, please download them from the docs repo, linked above, and add them to your project.

Webpack

We use Webpack to build Phaser and we take advantage of several features specific to Webpack to do this, including raw-loader to handle our shader files and build-time flags for renderer swapping.

If you wish to use Webpack with Phaser then please use our Phaser 3 Project Template as it's already set-up to handle the build conditions Phaser needs.

License

Phaser is released under the MIT License.

Getting Started

Phaser 3 is so new the "paint is still wet", but tutorials and guides are starting to come out!

Also, please subscribe to the Phaser World newsletter for details about new tutorials as they are published.

Source Code Examples

During our development of Phaser 3, we created hundreds of examples with the full source code and assets. Until these examples are fully integrated into the Phaser website, you can browse them on Phaser 3 Labs, or clone the examples repo. We are constantly adding to and refining these examples.

Create Your First Phaser 3 Example

Create an index.html page locally and paste the following code into it:

<!DOCTYPE html>
<html>
<head>
    <script src="https://labs.phaser.io/build/phaser-arcade-physics.min.js"></script> 
</head>
<body>

    <script></script>

</body>
</html>

This is a standard empty webpage. You'll notice there's a script tag that is pulling in a build of Phaser 3, but otherwise this webpage doesn't do anything yet. Now let's set-up the game config. Paste the following between the <script></script> tags:

var config = {
    type: Phaser.AUTO,
    width: 800,
    height: 600,
    physics: {
        default: 'arcade',
        arcade: {
            gravity: { y: 200 }
        }
    },
    scene: {
        preload: preload,
        create: create
    }
};

config is a pretty standard Phaser 3 Game Configuration object. We tell config to use the WebGL renderer if it can, set the canvas to a size of 800x600 pixels, enable Arcade Physics, and finally call the preload and create functions. preload and create have not been implemented yet, so if you run this JavaScript code, you will have an error. Add the following after config:

var game = new Phaser.Game(config);

function preload ()
{
    this.load.setBaseURL('http://labs.phaser.io');

    this.load.image('sky', 'assets/skies/space3.png');
    this.load.image('logo', 'assets/sprites/phaser3-logo.png');
    this.load.image('red', 'assets/particles/red.png');
}

function create ()
{
}

game is a Phaser Game instance that uses our configuration object config. We also add function definitions for preload and create. The preload function helps you easily load assets into your game. In preload, we set the Base URL to be the Phaser server and load 3 PNG files.

The create function is empty, so it's time to fill it in:

function create ()
{
    this.add.image(400, 300, 'sky');

    var particles = this.add.particles('red');

    var emitter = particles.createEmitter({
        speed: 100,
        scale: { start: 1, end: 0 },
        blendMode: 'ADD'
    });

    var logo = this.physics.add.image(400, 100, 'logo');

    logo.setVelocity(100, 200);
    logo.setBounce(1, 1);
    logo.setCollideWorldBounds(true);

    emitter.startFollow(logo);
}

Here we add a sky image into the game and create a Particle Emitter. The scale value means that the particles will initially be large and will shrink to nothing as their lifespan progresses.

After creating the emitter, we add a logo image called logo. Since logo is a Physics Image, logo is given a physics body by default. We set some properties for logo: velocity, bounce (or restitution), and collision with the world bounds. These properties will make our logo bounce around the screen. Finally, we tell the particle emitter to follow the logo - so as the logo moves, the particles will flow from it.

Run it in your browser and you'll see the following:

Phaser 3 Demo

(Got an error? Here's the full code)

This is a tiny example, and there are hundreds more for you to explore, but hopefully it shows how expressive and quick Phaser is to use. With just a few easily readable lines of code, we've got something pretty impressive up on screen!

Subscribe to our weekly newsletter for further tutorials and examples.

Building Phaser

There are both plain and minified compiled versions of Phaser in the dist folder of the repository. The plain version is for use during development, and the minified version is for production use. You can also create your own builds.

Custom Builds

Phaser 3 is built using Webpack and we take advantage of the Webpack definePlugin feature to allow for conditional building of the Canvas and WebGL renderers. As of Phaser 3.7 we have updated our webpack config to make our source far easier to consume in other package managers like Parcel and Electron. Please look our webpack config files to get an idea of the settings we use.

Building from Source

If you wish to build Phaser 3 from source, ensure you have the required packages by cloning the repository and then running npm install.

You can then run webpack to create a development build in the build folder which includes source maps for local testing. You can also run npm run dist to create a minified packaged build in the dist folder.

Change Log

Version 3.7.0 - Sinon - 8th May 2018

New Features

  • The Phaser 3 Labs has gained a nifty 'search' feature box thanks to @NemoStein - it allows you to filter out the example categories.
  • We've added a Mask component, which is available on nearly all Game Objects. It includes the methods setMask, clearMask, createBitmapMask and createGeometryMask.
  • CanvasTexture is a new extension of the Texture object specifically created for when you've got a Canvas element as the backing source of the texture that you wish to draw to programmatically using the Canvas API. This was possible in previous versions, as a Texture object supported having a Canvas as its source, but we've streamlined the process and made it a lot easier for you to refresh the resulting WebGLTexture on the GPU. To create a CanvasTexture just call the TextureManager.createCanvas method as before, only this time you'll get a CanvasTexture back which has helper properties and methods. See the complete JSDocs for more details.
  • RandomDataGenerator has a new method: shuffle which allows you to shuffle an array using the current RNG seed (thanks @wtravO)
  • The Texture Manager now supports normal maps for Atlas JSON (in both hash and array formats), Atlas XML and Atlas Unity.
  • All Game Objects have a new method disableInteractive which will disable the Interactive Object bound to them. You can toggle it back again by calling setInteractive with no arguments.
  • All Game Objects have a new method removeInteractive which will destroy the Interactive Object bound to them entirely. Use this if a Game Object no longer needs any input at all but you don't want to destroy the Game Object itself.

Loader New Features and Important Updates

The Loader has been given an overhaul to improve its performance and extensibility and gains the following new features:

  • A popular feature from Phaser 2 is back: Loader Packs. These are JSON files that contain a bunch of files to load. You can now load a pack into the Loader, and it will parse it and then add the contents into the current load queue automatically. Those contents can be anything the Loader can handle, including other packs! Please see the documentation and examples for more details.
  • The Loader is no longer locked during load. New files can be added into the load queue, even while a load is in process. Indeed, this is how the new Pack files feature works. A side effect is that if you do it a lot, your progress bar may jump around, as it's based on the number of files in the loader at that point in time. So if you add a bunch more it may look like it has reduced. It's up to you to handle this in your code, or create a type of loader graphic that doesn't highlight this (such as a spinning circle instead of a progress bar).
  • The Loader now handles the flow slightly differently. Before, it would load every file, and once they were all complete it would then process them in turn. Which would add them into the various caches, create textures, and so on. This now happens as soon as the file has loaded because the browser is likely mostly idle during this time anyway, so it allows us to distribute the file processing throughout the load time, rather than in one lump at the end.
  • Loading an Audio Sprite has changed. You now specify the JSON file first, and if you wish you can leave out the audio file URLs and let the Loader figure it out from the JSON meta data.
  • The Loader has a new file type: atlasXML which will load a Shoebox / Starling / Flash CC format XML Texture Atlas.
  • The Loader multiatlas file type has changed. You no longer have to specify the URLs of the images, instead it reads them from the JSON data and adds them into the loader automatically.
  • Every file type the Loader supports can now be loaded either via the method arguments, or a configuration object, or an array of configuration objects. Before only some of them could, but they all use the same code now. See the new examples demonstrating this.
  • If you used a Scene files payload then the format of the object has changed. It used to be a property in the Scene Config called files which was an array of files to load. It has been renamed to pack and it's an object that exactly matches the new Pack File format. Please see the loader example scene files payload.js for an example. In short, where you had: files: [] before, just change it to pack: { files: [] } and it'll work.
  • The Loader now supports Texture Atlases with normal maps. Before it would only support single images loaded with normal maps, but now you can provide them for all the atlas formats (json, xml and Unity)
  • The Loader multiatlas feature will now automatically load texture normal maps, if specified in the json.
  • Binary Files have a new optional dataType argument and property which will cast the binary data to that format after load, before inserting it into the cache, i.e.: load.binary('mod', 'music.mod', Uint8Array)
  • The method LoaderPlugin.tilemapWeltmeister has been renamed to the far more friendly LoaderPlugin.tilemapImpact. Everything else about it remains the same, but please update to use the new method name.

Loader Updates

  • The Loader and all associated file types are now covered 100% by JSDocs.
  • LinkFile is a new type of file used by the Loader that handles multiple files that need to be joined together. For example, loading a JSON and an Image for a Texture Atlas. This is now handled by a LinkFile.
  • File has a new argument in its constructor which is an instance of the LoaderPlugin. It stores this in the loader property. It also has a new property cache which is a reference to the cache that the file type will be stored in.
  • File has a new method hasCacheConflict which checks if a key matching the one used by this file exists in the target Cache or not.
  • File has a new method addToCache which will add the file to its target cache and then emit a filecomplete event, passing its key and a reference to itself to the listener (thanks to @kalebwalton for a related PR)
  • The Loader has a new property cacheManager which is a reference to the global game cache and is used by the File Types.
  • The Loader has a new property textureManager which is a reference to the global Texture Manager and is used by the File Types.
  • The Loader will now check to see if loading a file would cache a cache conflict or not, and prevent it if it will.
  • The Loader now hands off processing of the file data to the file itself, which will now self-add itself to its target cache.
  • The Loader will now call 'destroy' on all Files when it finishes processing them. They now tidy-up references and extra data, freeing them for gc.
  • The File Types are now responsible for adding themselves to their respective caches and any extra processing that needs to happen. This has removed all of the code from the Loader that was doing this, meaning the file types are now properly abstracted away and the Loader is no longer bound to them. This allows you to exclude file types if you don't need them, creating smaller bundles as a result. It also means we can drop in new file types easily without touching the Loader itself and Plugins can register new file types.
  • The XMLFile type will no longer throw an error if it can't parse the XML, instead it'll log a console warning and not add the XML to the cache.
  • Loading a BitmapFont will add the image used as the font texture into the Texture Manager and the XML into the XML cache, using the key you specified for the font, so you can extract it more easily if needed.
  • The default number of max parallel file loads has increased from 4 to 32. You can still change it in the game config.
  • Normal Maps can now be loaded using a config object: load.image({ key: 'shinyRobot', url: 'rob.png', normalMap: 'rob_n.png' }); - you can still use the previous array method too.
  • Loader.enableParallel has been removed. If you don't want parallel file loads then set the maximum parallel limit to 1. Related to this, the Game Config loaderEnableParallel property has been removed.
  • You can now set the X-Requested-With header in the XHR requests by specifying it in your XHRSettings config, either in the game, scene or file configs.
  • Files will consider themselves as errored if the xhr status is >= 400 and <= 599, even if they didn't throw an onerror event.

Updates

  • If you're using Webpack with Phaser you'll need to update your config to match our new one. The two changes are: We've removed the need for raw-loader and we've changed the syntax of the DefinePlugin calls:
  • We've swapped use of the Webpack DefinePlugin so instead of setting a global flag for the compilation of the Canvas and WebGL renderers, we use a typeof check instead. This means you should now be able to ingest the Phaser source more easily outside of Webpack without having to define any global vars (thanks @tgrajewski)
  • Under Webpack we still no longer use raw-loader to import our shader source. Instead it's compiled to plain JS files during our in-house workflow. This should allow you to bundle Phaser with packages other than Webpack more easily.
  • The Texture Manager will now emit an addtexture event whenever you add a new texture to it, which includes when you load image files from the Loader (as it automatically populates the Texture Manager). Once you receive an addtexture event you know the image is loaded and the texture is safe to be applied to a Game Object.
  • BitmapMask and GeometryMask both have new destroy methods which clear their references, freeing them for gc.
  • CanvasPool has a new argument selfParent which allows the canvas itself to be the parent key, used for later removal.
  • Frame has a new method setSize which allows you to set the frame x, y, width and height and have it update all of the internal properties automatically. This is now called directly in the constructor.
  • When a TextureSource is destroyed if it's got a canvas texture it's removed from the CanvasPool.
  • TextureManager.checkKey will check if a texture key is in-use and log a console error if it is and then return a boolean. This is now used extensively internally to prevent you from adding textures that already exist into the manager. If you wish to just check if a key is in use without the error, use the TextureManager.exists method as before.
  • TextureManager.remove will allow you to remove a texture from the manager. The texture is destroyed and it emits a removetexture event.
  • TextureSource has a new property renderer as it's used a lot internally and is useful if you extend the class.
  • TextureSource will now remove its respective WebGLTexture from the renderer when destroyed.
  • TextureSource will now automatically create a glTexture from its canvas if using one.
  • WebGLRenderer will now remove a GL texture from its local nativeTextures array when you call the deleteTexture method.
  • The BaseCache has a new method exists that will return a boolean if an entry for the given key exists in the cache or not.
  • ScenePlugin.getIndex will return the index of the given Scene in the Scene List.
  • The Scene Systems will emit a ready event when it has fully finished starting up and all plugins are available. Re: #3636 (thanks @Yazir)
  • All Game Object Creators now have an extra boolean argument addToScene. If you set this to true it will add the Game Object being created to the Scene automatically, while false will do the opposite, i.e.: this.make.image(config, false). You can still specify the add property in the Config object too, but if the argument is provided it will override the property.
  • We have removed the TextureManager.addAtlasPyxel method and related parser. It didn't work anyway and no-one seems to use Pyxel any more. If we get enough demand we can consider adding it back.
  • When adding an Audio Sprite to the Sound Manager it will now respect the loop property, if set in the source JSON.
  • The Texture class has a new method getDataSourceImage which will return the raw image data of the data source.
  • The WebAudioSoundManager will now listen for 'click' events on the document body, as well as touch events, before resuming the AudioContext, in order to deal with the changes made in Chrome v66 not playing audio until a user gesture is received, even on desktop.

Bug Fixes

  • DataManagerPlugin would throw an error on Game.destroy if you had any Scenes in the Scene Manager had not been run. Fix #3596 (thanks @kuoruan)
  • If you created a Game with no Scenes defined, and then added one via Game.scene.add and passed in a data object, the data would be ignored when starting the Scene.
  • Adding a Group with an array of children in the constructor was broken since 3.5. Fix #3612 (thanks @fariazz @samme)
  • Fix ParticleEmitter toJSON output, it was missing the angle property and the Emitter Ops were being cast wrong (thanks @samme)
  • Fixed loading normals with multi image load (thanks @iamchristopher)
  • Array.AddAt would fail if it branched to the fast-path within a Container due to an invalid property. Fix #3617 (thanks @poasher)
  • Polygon.setTo would fail if given an array of arrays as a list of points. Fix #3619 (thanks @PaulTodd)
  • Text objects with word wrapping enabled would gain an extra space at the end of the line. These are now only added when the word index is greater than the previous one. Fix #3626 (thanks @rexrainbow)
  • Container.getBounds now checks if it can call getBounds on its children before doing so, as some do not have this method (such as Graphics objects) so they no longer cause the call to crash. Fix #3623 (thanks @poasher)
  • The Animation Component setProgress method was setting the frame on the wrong object. Fix #3633 (thanks @benhhopkins)
  • SceneManager.moveAbove wouldn't move the Scene if it was already above the target Scene. Now it moves to be directly above the target Scene no matter where in the Scene List it is.
  • SceneManager.moveBelow wouldn't move the Scene if it was already below the target Scene. Now it moves to be directly below the target Scene no matter where in the Scene List it is.
  • Emitter.setEmitZone was rejecting custom objects passed as the source argument because it was checking for the wrong methods (thanks @samme)
  • ScenePlugin.setActive would only toggle the current Scene, not any given Scene.
  • ScenePlugin.setVisible would only toggle the current Scene, not any given Scene.
  • The Graphics Creator would automatically add the Graphics to the display list by mistake. The default should be to remain hidden. Fix #3637 (thanks @mikuso)
  • BitmapText, both static and dynamic, can now take any data-type, including numbers, for the text argument in the constructor. Before they only worked via setText (thanks @Jelaw21)
  • The Forward Diffuse Light Pipeline was hard coded to assume the normal map would be stored in the source index zero. It now correctly obtains the normal map from the frame source index, which means all Game Objects that used frames from multi-atlas textures will now work with lights properly.
  • The Tiled Base64Decode function worked off the wrong array length, causing extra undefined values at the end (thanks @tamagokun)

Examples, Documentation and TypeScript

My thanks to the following for helping with the Phaser 3 Examples, Docs and TypeScript definitions, either by reporting errors, fixing them or helping author the docs:

@wtravO @Fabadiculous @zilbuz @samme @iamchristopher @erd0s @PaNaVTEC @ksmai @snowbillr

Please see the complete Change Log for previous releases.

Looking for a v2 change? Check out the Phaser CE Change Log

Contributing

The Contributors Guide contains full details on how to help with Phaser development. The main points are:

  • Found a bug? Report it on GitHub Issues and include a code sample. Please state which version of Phaser you are using! This is vitally important.

  • Before submitting a Pull Request run your code through ES Lint using our config and respect our Editor Config.

  • Before contributing read the code of conduct.

Written something cool in Phaser? Please tell us about it in the forum, or email support@phaser.io

Created by

Phaser is a Photon Storm production.

storm

Created by Richard Davey. Powered by coffee, anime, pixels and love.

The Phaser logo and characters are © 2018 Photon Storm Limited.

All rights reserved.

"Above all, video games are meant to be just one thing: fun. Fun for everyone." - Satoru Iwata