Subscribe to GameFromScratch on YouTube Support GameFromScratch on Patreon

17. September 2015


Right off the hop, that title is a bit misleading…  Phaser doesn’t really support GLSL shaders, or at least not by that name.  What it supports is Filters, which it inherits from the Pixi renderer.  Right off the hop you should be aware that this only works on the WebGL renderer, so the fallback canvas renderer cannot and probably never will support filters.


This process isn’t overly difficult, but as far as I’ve been able to tell, there are no existing examples on using shaders/filters in Phaser with Typescript, so a few of the TypeScript specific aspects can cause a bit of a stumbling block.  For this first example I am simply going to port the gray filter example to TypeScript.  This filter simply turns whatever it is attached to gray, simple enough.  Let’s jump right in with the code:

/// <reference path="phaser.d.ts"/>

class Uniforms {
    gray: any;
class MyShader extends Phaser.Filter {

    uniforms: Uniforms;

    constructor(game: Phaser.Game, uniforms: any, fragmentSource: string[]) {
        this.uniforms = new Uniforms();
        this.uniforms.gray = { type: '1f', value: 1.0 };

        this.fragmentSrc = [

            "precision mediump float;",

            "varying vec2       vTextureCoord;",
            "varying vec4       vColor;",
            "uniform sampler2D  uSampler;",
            "uniform float      gray;",

            "void main(void) {",
            "gl_FragColor = texture2D(uSampler, vTextureCoord);",
            "gl_FragColor.rgb = mix(gl_FragColor.rgb, vec3(0.2126 * gl_FragColor.
                                r + 0.7152 * gl_FragColor.g + 0.0722 * 
                                gl_FragColor.b), gray);",

        super(, this.uniforms, this.fragmentSrc);


class SimpleGame {
    game: Phaser.Game;
    image: Phaser.Sprite;
    myShader: MyShader;

    constructor() { = new Phaser.Game(640, 480, Phaser.AUTO, 'content', {
            create: this.create, preload:
            render: this.render
    preload() {"logo","GFSLogo.png");
    render() {
    create() {
        this.image =, 0, "logo");
        this.image.filters = [new MyShader(, null, null)];

window.onload = () => {
    var game = new SimpleGame();


The major difference here is we inherit from the Phaser.Filter class.  One other major difference, since TypeScript is a typed language, we need to specify our Uniforms as a class.  I took the lazy approach and made each parameter an any.  uniforms are paramaters passed in to the shader, although in this case Phaser itself passed in the value for vTextureCoord, vColor and uSampler.  It’s through using uniforms that your game logic can control the actions of the shader.


Next we define the fragment shader source as an array of strings.  Fragment shaders can be thought of little mini shader programs that are executed for each potentially drawn pixel in the resulting image.  This particular shader simply samples the current pixel at the current location within the texture and multiplies that value’s rgb by a slightly more “gray” version of itself.  gl_FragColor can be thought of as the return type of the fragment shader, and it contains that pixel to be displayed.  A discussion of GLSL is way beyond the scope of this tutorial but more details and resources are available here.


Finally in the actual game code you can see how the shader is applied to the image we loaded:

this.image.filters = [new MyShader(, null, null)];

The .filters member is an array, so multiple filters can be applied if desired.  When you run this example you should see:



You can apply different shaders by changing the fragmentSrc value, just keep in mind you need to setup each parameter in the Uniforms class.


If the idea of encoding your shaders into a string array is off putting, there exists code to load shaders from file.

Programming ,

29. March 2015


The popular HTML5 library Phaser have just released 2.3.  It’s not a huge new functionality release, but it’s got some major architecture changes that will affect you greatly if you are a Phaser user.  First off, they went down a more modular approach leading to fewer god classes.  This is aPhaser 2.3.0 good thing™.  Then thanks to this redesign, they also made the Phaser build process different, allow you to disuse unneeded portions.


From the release notes:


Significant Updates



All of the core Game Objects have received an important internal restructuring. We have moved all of the common functions to a new set of Component classes. They cover functionality such as 'Crop', 'Physics Body', 'InCamera' and more. You can find the source code to each component in the src/gameobjects/components folder of the repo.

All of the Game Object classes have been restructured to use the new component approach. This puts an end to the "God classes" structure we had before and removes literally hundreds of lines of duplicate code. It also allowed us to add features to Game Objects; for example Bitmap Text objects are now full-class citizens with regard to physics capabilities.

Although this was a big internal shift from an API point of view not much changed - you still access the same methods and properties in the same way as before. Phaser is just a lot leaner under the hood now.

It's worth mentioning that from a JavaScript perspective components are mixins applied to the core game objects when Phaser is instantiated. They are not added at run-time or are dynamic (they never get removed from an object once added for example). Please understand that this is by design.

You can create your own custom Phaser classes, with your own set of active components by copying any of the pre-existing Game Objects and modifying them.



As a result of the shift to components we went through the entire source base and optimised everything we could. Redundant paths were removed, debug flags removed and new stub classes and hooks were created. What this means is that it's now easier than ever to "disable" parts of Phaser and build your own custom version.

We have always included a couple of extra custom builds with Phaser. For example a build without P2 Physics included. But now you can strip out lots of additional features you may not require, saving hundreds of KB from your build file in the process. Don't use any Sound in your game? Then you can now exclude the entire sound system. Don't need Keyboard support? That can be stripped out too.

As a result of this work the minimum build size of Phaser is now just 83KB (minified and gzipped).

Please see this tutorial on how to create custom builds.



We've updated the core of Arcade Physics in a number of significant ways.

First we've dropped lots of internal private vars and moved to using non-cached local vars. Array lengths are no longer cached and we've implemented physicsType properties on Game Objects to speed-up the core World collideHandler. All of these small changes have lead to a nice improvement in speed as a result, and also allows us to now offer things like physics enabled BitmapText objects.

More importantly we're now using a spacial pre-sort for all Sprite vs. Group and Group vs. Group collisions. You can define the direction the sort will prioritize via the new sortDirection property. By default it is set to Phaser.Physics.Arcade.LEFT_RIGHT. For example if you are making a horizontally scrolling game, where the player starts on the left of the world and moves to the right, then this sort order will allow the physics system to quickly eliminate any objects to the right of the player bounds. This cuts down on the sheer volume of actual collision checks needing to be made. In a densely populated level it can improve the fps rate dramatically.

There are 3 other directions available (RIGHT_LEFT, TOP_BOTTOM and BOTTOM_TOP) and which one you need will depend on your game type. If you were making a vertically scrolling shoot-em-up then you'd pick BOTTOM_TOP so it sorts all objects above and can bail out quickly. There is also SORT_NONE if you would like to pre-sort the Groups yourself or disable this feature.

Another handy feature is that you can switch the sortDirection at run-time with no loss of performance. Just make sure you do it before running any collision checks. So if you had a large 8-way scrolling world you could set the sortDirection to match the direction the player was moving in and adjust it in real-time, getting the benefits as you go. My thanks to Aaron Lahman for inspiring this update.



The Phaser.Loader has been updated to support parallel downloads which is now enabled by default (you can toggle it via the Loader.enableParallel flag) as well as adding future extensibility points with a pack/file unified filelist and an inflight queue.

There are no known incompatibilities with the previous Loader. Be aware that with parallel downloading enabled the order of the Loader events may vary (as can be seen in the "Load Events" example).

The parallel file concurrency limit is available in Loader.maxParallelDownloads and is set to 4 by default. Under simulated slower network connections parallel loading was a good bit faster than sequential loading. Even under a direct localhost connection parallel loading was never slower, but benefited most when loading many small assets (large assets are more limited by bandwidth); both results are fairly expected.

The Loader now supports synchronization points. An asset marked as a synchronization point must be loaded (or fail to load) before any subsequent assets can be loaded. This is enabled by using the withSyncPoint and addSyncPoint methods. Packs ('packfile' files) and Scripts ('script' files) are treated as synchronization points by default. This allows parallel downloads in general while allowing synchronization of select resources if required (packs, and potentially other assets in the future, can load-around synchronization points if they are written to delay final 'loading').

Additional error handling / guards have been added, and the reported error message has been made more consistent. Invalid XML (when loading) no longer throws an exception but fails the particular file/asset that was being loaded.

Some public methods/properties have been marked as protected, but no (except in case of a should-have-been-private-method) public-facing interfaces have been removed. Some private methods have been renamed and/or removed.

A new XHR object is created for each relevant asset (as there must be a different XHR for each asset loaded in parallel). Online searches indicated that there was no relevant benefit of XHR (as a particular use-case) re-use; and time will be dominated with the resource fetch. With the new flight queue an XHR cache could be re-added, at the cost of some complexity.

The URL is always transformed through transformUrl, which can make adding some one-off special cases like #1355 easier to deal with.

This also incorporates the fast-cache path for Images tags that can greatly speed up the responsiveness of image loading.

Loader.resetLocked is a boolean that allows you to control what happens when the loader is reset, which happens automatically on a State change. If you set resetLocked to true it allows you to populate the loader queue in one State, then swap to another State without having the queue erased, and start the load going from there. After the load has completed you could then disable the lock again as needed.

Thanks to @pnstickne for vast majority of this update.



We are now using our own custom build of Pixi v2. The Pixi project has moved all development resources over to Pixi v3, but it wasn't ready in time for the release of Phaser 2.3 so we've started applying our own fixes to the version of Pixi that Phaser uses.

As a result we have removed all files from the src/pixi folder that Phaser doesn't use, in order to make this distinction clearer. This includes EventTarget, so if you were relying on that in your game you'll need to add it back in to your local build.

We've also removed functions and properties from Pixi classes that Phaser doesn't require: such as the Interaction Manager, Stage.dirty, etc. This has helped us cut down the source code size and make the docs less confusing, as they no longer show properties for things that weren't even enabled.

We've rolled our own fixes into our version of Pixi, ensuring we keep it as bug-free as possible.

You can read the entire release notes here.

Programming, News ,

12. March 2015


I’ve long been a fan of the Phaser HTML5 game library, as my ongoing tutorial series might indicate.  Somewhat recently Phaser started adding premium commercial plugins.  The most recently added plugin adds support for Box2D, the popular 2D physics based library.  This is a commercial plugin (aka, you’ve got to pay for it.  $65 for premium $45 for standard – only difference is number of samples ), but don’t fret, Phaser still has a number of physics systems built-in that are completely free.


Box2D is a feature-rich 2D physics system used by thousands of hit games.

This plugin opens-up the power of Box2D directly within Phaser. It has the same user-friendly approach to its API that the rest of Phaser does, making integration and game development a beeze.


It uses the excellent box2d-html5 JavaScript port by Isaac Burns. We found that this library had the best performance of those tested, even on mobile.

Development of the plugin was lead by Box2D experts iForce2D - the company responsible for the excellent Box2D visual editor R.U.B.E


See the Box2D Plugin Page for More Details


The Download includes

  • Getting Started Guide - You'll be coding in next to no time.
  • 90 Code Examples - From games to core mechanics.
  • API Documentation and Box2D User Manual
  • Free Upgrades
  • License free - Use it in commercial games
  • Ready built and minified source files + grunt scripts
  • Delivered via download from

Try it out

We've added 40 of the Box2D examples to this site.

Run them, play with them and edit the code to get a feel for how it all works.


The full release details are available here.


I actually like to see this form of monetization.  Developers need to eat and we want  them working to make better and better products.  Keeping the core free while adding premium but optional features as a premium plug-in seems like a good middle line to me.  The key is to keep developing the core free product at the same rate that commercial plugins are added.

News , ,

15. January 2015


I’ve been doing a long running Phaser with TypeScript tutorial series that illustrates basically everything you need to know to create a complete game using the Phaser HTML5 game engine.  I decided to put together a video tutorial showing how to put it all together to make a complete game.


Now, keep in mind, the game is incredibly simple… I wanted to keep the entire thing to under an hour after all ( I failed, it’s an hour and a half ), so I had to keep the scope reasonable in size.  So as a result I’ve created Extreme Walking Simulator!  Yeah, you walk… and that’s it actually.  You walk forever and ever in front of the same looping background.  However, you are left with a complete but simple game but most importantly, a framework of code that can be expanded upon to build much more complex games.  It also illustrates program flow, drawing sprites, playing music, changing states, handling input and all the other things a “full” game has to do.


In addition to the code, all of the assets used are available on GitHub.  This includes my incredible title music, the Blend files used for the main character and the level scene.  Everything you need to create this game is there in the Assets folder.  Feel free to play around and use it however you want.  That said, the textures just came from Google Image Search, so no clue if there is a copyright on any of them, so don’t use them in a commercial project! I believe all of my Github stuff is set to Creative Commons license…  if it’s not, assume you can do anything you want with it and that you have absolutely no warranty.


Ok, enough preamble, let’s jump right in!  The tutorial is available in two parts on YouTube in 1080p ( or embedded below):



Following are the game itself, then the source listings, finally the two videos in an embedded player.




EDIT: Removed to prevent music auto playing, to play the game click here instead. Warning, loud


  • Click the title screen to get started
  • Tap right arrow to start walking/speed up
  • Tap left arrow to slow down/stop
  • Press ESC to stop the torture!



The Source Code



<!DOCTYPE html>

<html lang="en">
    <meta charset="utf-8" />
    <title>Hello Phaser</title>
    <link rel="stylesheet" href="app.css" type="text/css" />
    <script src="phaser.js"></script>
    <script src="GameObjects/MyScene.js"></script>
    <script src="GameObjects/Player.js"></script>
    <script src="States/TitleScreenState.js"></script>
    <script src="States/GamePlayState.js"></script>
    <script src="States/GameOverState.js"></script>
    <script src="app.js"></script>
    <div id="content"></div>



module Game {
    export class ExtremeWalkingSimulator {
        game: Phaser.Game;

        constructor() {
   = new Phaser.Game(1280, 720, Phaser.AUTO, 'content', {
                create: this.create, preload: this.preload

        preload() {
            // Graphics
  "title", "Graphics/TitleScreen.png");
  "scene", "Graphics/scene720p.png");
  "gameover", "Graphics/GameOver.png");

  "HERO_WALKING", "Graphics/Hero_Walking.png", "Graphics/Hero_Walking.xml");
  "HERO_IDLE", "Graphics/Hero_Idle.png", "Graphics/Hero_Idle.xml");

            // Audio
  "TitleSong", ["Sounds/TitleSong.mp3", "Sounds/TitleSong.ogg",
"Sounds/TitleSong.wav"]); } create() {"TitleScreenState", GameFromScratch.TitleScreenState, true);"GamePlayState", GameFromScratch.GamePlayState, false);"GameOverState", GameFromScratch.GameOverState, false); = Phaser.ScaleManager.SHOW_ALL; } } } window.onload = () => { var game = new Game.ExtremeWalkingSimulator(); };



module GameFromScratch {
    export enum PlayerState { IDLE, WALKING }

    export class Player extends Phaser.Sprite {
        game: Phaser.Game;
        playerState: PlayerState;
        RIGHT_ARROW: Phaser.Key;
        LEFT_ARROW: Phaser.Key;
        ESCAPE: Phaser.Key;
        walkingSpeed: number;

        public static MAX_SPEED: number = 30;

        constructor(game: Phaser.Game, x: number, y: number) {
   = game;

            this.walkingSpeed = 0;

            //Wire up input handlers
            this.RIGHT_ARROW =;
            this.RIGHT_ARROW.onDown.add(Player.prototype.MoveRight, this);

            this.LEFT_ARROW =;
            this.LEFT_ARROW.onDown.add(Player.prototype.MoveLessRight, this);

            this.ESCAPE =;
            this.ESCAPE.onDown.add(Player.prototype.GameOver, this);
            super(game, x, y, "HERO_WALKING", 0);

            this.anchor.set(0.0, 1.0);

        update() {
            if (this.playerState == PlayerState.WALKING) {
                this.x += (this.walkingSpeed / Player.MAX_SPEED) * (60 /;

                // This logic depends on scene being added first.
                var stageWidth =;
                if (this.x > stageWidth * .75)
                    this.x = stageWidth * .25;

        // Worse function name ever!
        MoveLessRight() {
            if (this.playerState != PlayerState.IDLE) {
                if (this.walkingSpeed > 0)
                    this.animations.currentAnim.speed = this.walkingSpeed;

        MoveRight() {
            if (this.playerState == PlayerState.IDLE) {
            else {
            if (this.walkingSpeed < Player.MAX_SPEED)
                this.animations.currentAnim.speed = this.walkingSpeed;

        StartWalking() {
            this.playerState = PlayerState.WALKING;
            this.walkingSpeed = 5;
            this.loadTexture("HERO_WALKING", 0);
  "walk", this.walkingSpeed, true);

        StartIdle() {
            this.loadTexture("HERO_IDLE", 0);
            this.playerState = PlayerState.IDLE;

        GameOver() {




module GameFromScratch {

    export class MyScene extends Phaser.Sprite {
        game: Phaser.Game;
        nextFrame: Phaser.Sprite;

        constructor(game: Phaser.Game, x: number, y: number) {
            super(game, x, y, "scene", 0);
            this.nextFrame = new Phaser.Sprite(, this.width, 0, "scene", 0);



module GameFromScratch {
    export class TitleScreenState extends Phaser.State {
        game: Phaser.Game;
        music: Phaser.Sound;

        constructor() {

        titleScreenImage: Phaser.Sprite;

        preload() {

        create() {
            this.titleScreenImage = this.add.sprite(0, 0, "title");
this.titleScreenImage.height); ="TitleSong"); = 100; = true;; this.input.onTap.addOnce(this.titleClicked, this); } titleClicked() {;"GamePlayState"); } } }



module GameFromScratch {
    export class GamePlayState extends Phaser.State {
        game: Phaser.Game;
        player: GameFromScratch.Player;
        myScene: GameFromScratch.MyScene;

        constructor() {

        preload() {
        create() {
            this.myScene = new MyScene(, 0, 0);
            this.player = new Player(, 0, - 50);


  ,0,this.myScene.width * 2, this.myScene.height);



module GameFromScratch {
    export class GameOverState extends Phaser.State {
        game: Phaser.Game;
        gameOverSprite: Phaser.Sprite;

        constructor() {

        preload() {
        create() {
            this.gameOverSprite = this.add.sprite(0, 0, "gameover", 0);
            this.gameOverSprite.scale.setTo( / this.gameOverSprite.width, /
this.gameOverSprite.height); this.input.onDown.add(() => {"TitleScreenState", true); }, this);; } } }




The Videos


Part One:


Part Two:

Programming , , , , ,

7. January 2015


It’s most a maintenance release, so the list of new features is fairly sparse:


New Features
  • Phaser.Loader now supports BLOB urls for audio files (thanks @aressler38 #1462)
  • Line.reflect will calculate the reflected, or outgoing angle of two lines. This can be used for Body vs. Line collision responses and rebounds.
  • Line.normalAngle gets the angle of the line normal in radians.
  • Line.normalX and Line.normalY contain the x and y components of the left-hand normal of the line.
  • Line.fromAngle will sets this line to start at the given x and y coordinates and for the segment to extend at angle for the given length.
  • BitmapData.drawGroup draws the immediate children of a Phaser.Group to a BitmapData. Children are only drawn if they have their exists property set to true. The children will be drawn at their x and y world space coordinates. When drawing it will take into account the child's rotation, scale and alpha values. No iteration takes place. Groups nested inside other Groups will not be iterated through.


You can read the complete release notes here.


The release 2.3 milestones are available here.


They also made this announcement regarding version 3:

We're hard at work on Phaser 3. Development on the brand new renderer began in earnest last year and we're already seeing exceptional results from it. You can follow our development in the forum and public repo. Even though we're working on taking Phaser 3 into ES6 and the next generation of web browsers, we haven't stopped with the 2.x branch.


If Phaser sounds interesting to you, of course, Gamefromscratch has an extensive tutorial series available here.

Programming, News , ,

Month List

Popular Comments