Create HTML5 Vertical Endless Runner cross platform games

Using Phaser framework and other FREE software
Endless runner games are gaining more and more popularity and they are really easy to code.
I will take you by hand through the creation of a complete HTML5 vertical endless runner cross platform game with a lot of features and room for customization.
100 pages + 31 source code examples with a free update to come in a few days.

Phaser Tutorial: understanding Phaser states

Emanuele Feronato Game design, HTML5, Javascript, Phaser

During these days I am using Phaser for a series of projects, and one feature I found really interesting is state management.

How can we use Phaser states in game development? Basically, if you divide a game into “blocks”, such as splash screen, main menu, the game itself and so on, each of these “blocks” can be developed as a state.

Nothing you can’t do with just plain coding, but if you consider states management flushes the memory, releases resources, removes listeners and manages garbage collection, you will definitively want to use them in your games.

Before the tutorial starts, I want you to play this little game:

The concept is very simple: there’s a random number from 0 to 9 on the screen, and you have to guess if next number drawn will be higher or lower than the number currently displayed.

Each time you guess right you get one point, and the first time you fail, it’s game over and you will see the score. My best score is 12, for your information.

Now, let’s dissect the game:

As you can see there’s a preloading bar, then a menu screen, then the game itself and the game over screen which calls once again the game itself.

Each of these screens will be represented as a state, so our game will have four states + one special state you will meet in a matter of minutes.

Let’s see the content of index.html file:

This is quite easy, first we load phaser library:

then all the files where states code is stored

I saved each state in a separate file. This is not strictly needed, but it will keep your code more organized and reusable. Notice we have five files, just like the four states + one special state.

States declaration is made by game.state.add: the first argument is the name of the state, while the second is the name of the function to call inside such state.

Finally, we launch the initial state, Boot, with game.state.start

Since Boot state is the first state we are calling, let’s have a look at boot.js:

Boot is our special state: it just adjusts stage size and scale. If you notice, its behavior is not different than a Phaser game: it features preload and create functions. At this time, I am only preloading the loading bar image. Once everything is ready, we pass to Preload state, so here we go with preload.js:

This function is the actual game preloader, and as you can see all graphic assets are preloaded now. The only interesting feature is that at preloading time I am also placing on the stage the loading bar previously loaded in Boot state:

With load.setPreloadSprite method, Phaser will act like the sprite we passed as argument was an actual loading bar, setting its width longer as the preloading goes on.

Once all assets have been preloaded, it’s time to pass to GameTitle state, located in gametitle.js:

Now the game title has been placed, along with a “play” button that once pressed jumps to TheGame, located in thegame.js:

And now it should be clear how states work, explaining how the game itself works is beyond the scope of this post, but I want you to focus on the way I am calling GameOver state:

This is the first time I am calling the state with all its arguments, so let’s have a look at them:

GameOver is the name of the state to start

the second argument is called clearWorld, default at true, and clears the World display list fully (but not the Stage, so if you’ve added your own objects to the Stage they will need managing directly).

the third argument is called clearCache, default at false, and clears all loaded assets. You won’t use it that often as we want to keep loaded assets.

all other parameters from the fourth are variables that will be passed to the init function (if it has one). So I am going to pass the score to GameOver state, have a look at gameover.js:

Do you see init function?

That’s how I print out (actually I alert) the score.

And that’s all with the states, hope you will use them in your next project as they are really useful. And obviously you can download the source code of the entire project to study it.

Stay up to date
Follow me on the social networks and never miss a post.

Official Emanuele Feronato Facebook page

Official Emanuele Feronato Twitter account

From null to full HTML5 cross platform game

I will take you by hand from the bare bones of JavaScript programming through the creation of a full cross platform HTML5 game, with detailed explainations and source code.

If you don't know where to start, then From null to full HTML5 cross platform game is the book for you.

Comments 24

    1. Post
      Author
  1. Pingback: Phaser Tutorial: creating your own Phaser plugins - Emanuele Feronato

  2. Ousaf

    var boot = function(game){
    console.log(“%cStarting my awesome game”, “color:white; background:red”);
    };

    boot.prototype = {
    preload: function(){
    this.load.image(“loading”,”assets/loading.png”);
    },
    create: function(){
    this.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
    this.scale.pageAlignHorizontally = true;
    this.scale.setScreenSize();
    this.state.start(“Preload”);
    }
    }

    I think Boot.js code should look like this as ‘this.game’ is replaced by ‘this’ only as it references to game object

    1. abesmon

      Nope, this. refers to a State object, so to get game object, we need to call this.game. Take a look – call console.log(this) in create method, and u`l see :)

  3. Shantanu

    Hello Emmanuel,

    Just wanted to know how to access variables from one of my files in another file?

    For example:
    If I have a variable “score” declared in my “TitleScreen.js” file and I want to access this variable in my “game.js” how can I do it?

    Regards.

    1. Post
      Author
  4. Pingback: HTML5 Phaser Tutorial: how to create a level selection screen with locked levels and stars – finished prototype | Phaser??

  5. Pingback: Understanding Unity3D scenes | Emanuele Feronato

  6. Ruslan

    What is the difference between var state = function() {}; and var state = {};. I white all code in one file.

    1. Post
      Author
      1. Ruslan

        Sorry, I still don’t understand. I create game states like objects (var playGame = {preload: etc…};), without functions and prototypes and it works.

        1. Post
          Author
          Emanuele Feronato

          Sure, it can work this way too, but this way you can only have ONE “preload”, ONE “create”, ONE “update”

  7. Omarojo

    Hi, thanks for the tutorial. Im having troubles when I do state switching using ‘ this.state.start(‘SlideShow’, true,false);

    When the SlideShow state appears on screen.. I see the previous state objects still being rendered. So I dont undertand when you say: ” clearWorld, default at true, and clears the World display list fully (but not the Stage, so if you’ve added your own objects to the Stage they will need managing directly)”.

    What is the WORLD ? and what is the STAGE ? Im just using this.add.sprite… how do I know if that is in the world or in the stage ? (where the state anyway )

    Thanks

  8. Breno

    Emanuele, when a state is called, the phaser will clean the older state. For example, when the user clicks on the play button, I need to delete the objects of the menu screen?

  9. Rahel Schmied

    Hi, everything with the state stuff works just fine now (: thank you!!

    I happen to have a button Problem though… could you help me?

    I have a Start Background ( startsc) witch is loading just fine….
    And than i have a Button(start) witch is giving me the following error message:
    Uncaught Error: Phaser.Signal: listener is a required param of add() and should be a Function.
    I have no idea why…. do you have any idea?

    var startMenu = function(game){};

    startMenu.prototype = {
    preload: function(){

    this.game.load.image(‘startsc’, ‘../assets/startsc.png’);
    this.game.load.image(‘start’, ‘../assets/start.png’);

    },
    create: function(){

    var gameTitle = this.game.add.sprite(0,0,”startsc”);
    var startButton = this.game.add.button(this.game.world.centerX,this.game.world.centerY,”start”, this.load, this);
    this.startButton.anchor.setTo(0.5,0.5);

    },
    load: function(){
    this.game.state.start(“preload”);
    }

    }

    1. Post
      Author
      Emanuele Feronato

      if you don’t include game creation in an window.onload event, just place these lines

      var game = new Phaser.Game( 800, 600, Phaser.AUTO, '' );
      game.state.add( 'load', load );
      game.state.add( 'play', play );
      game.state.start( 'load' );

      at the end of the script

  10. Vincent Huss

    it would be interesting to explain more about how Phaser handle states, the order of calls (i had to make my own tests to find out that init is called before create). You stay on the surface in this article, too bad:(

Leave a Reply

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