Phaser is a framework for creating 2D video games. It uses HTML5 Canvas to display the game and JavaScript to run the game. The benefit of using Phaser over vanilla JavaScript is that has an extensive library that completes much of the physics of video games allowing you to concentrate on designing the game itself.

Phaser reduces development time and eases workflow. Let's learn how to create a basic game with Phaser.

Why Develop With Phaser?

Phaser is similar to other visual programming languages in that the program is based on looped updates. Phaser has three main stages: preload, create, and update.

In preload, the game's assets are uploaded and made available to the game.

Create initializes the game and all of the starting game elements. Each of those functions are run once when the game is started.

Update, on the other hand, runs in a loop throughout the game. It is the workhorse that updates the elements of the game to make it interactive.

Set Up Your System for Developing Games With Phaser

Despite that Phaser runs on HTML and JavaScript, the games are actually run server-side, not client-side. This means that you will need to run your game on your localhost. Running the game server-side allows your game to access additional files and assets outside of the program. I recommend using XAMPP to set up a localhost if you do not already have one setup.

The code below will get you up and running. It sets up a basic game environment.

         <html>
  <head>
    <script src="//cdn.jsdelivr.net/npm/phaser@3.24.1/dist/phaser.js"></script>
  </head>
  <body>
    <script>
    var config = {
      type: Phaser.AUTO,
      backgroundColor: 0xCCFFFF,
      width: 600,
      height: 600,
      physics: {
        default: 'arcade'
      },
      scene: {
        preload: preload,
        create: create
      }
    };
 
    var gamePiece;
    var game = new Phaser.Game(config);
 
    function preload(){
      this.load.image('gamePiece', 'img/gamePiece.png');
    }
 
    function create(){
      gamePiece = this.physics.add.sprite(270, 450, 'gamePiece');
    }
    </script>
  </body>
</html>

To run, the game will require a PNG image called "gamePiece" saved to an "img" folder on your localhost. For simplicity, this example uses a 60xgame de60px orange square. Your game should look something like this:

basic phaser game

If you run into an issue, use your browser's debugger to figure out what went wrong. Missing even a single character can cause havoc, but generally, your debugger will catch those little errors.

Explaining The Setup Code

So far, the game doesn't do anything. But we have already covered a lot of ground! Let's look at the code more in-depth.

For a Phaser game to run, you need to import the Phaser library. We do this on line 3. In this example, we linked to the source code, but you can download it to your localhost and reference the file too.

Much of the code so far configures the game environment, which the variable config stores. In our example, we are setting up a phaser game with a blue (CCFFFF in hex color code) background that is 600px by 600px. For now, the game physics have been set to arcade, but Phaser offers different physics.

Finally, scene tells the program to run the preload function before the game starts and the create function to start the game. All of this information is passed to the game object called game.

Related: The 6 Best Laptops for Programming and Coding

The next section of code is where the game really takes shape. The preload function is where you want to initialize anything that you need to run your game. In our case, we have preloaded the image of our game piece. The first parameter of .image names our image and the second tells the program where to find the image.

The gamePiece image was added to the game in the create function. Line 29 says that we are adding the image gamePiece as a sprite 270px left and 450px down from the top left corner of our game area.

Making Our Game Piece Move

So far, this can hardly be called a game. For one thing, we can't move our game piece. To be able to change things in our game, we will have to add an update function. We will also have to adjust the scene in the config variable to tell the game which function to run when we update the game.

Adding An Update Function

New scene in config:

        scene: {
  preload: preload,
  create: create,
  update: update
}

Next, add an update function below the create function:

        function update(){
}

Getting Key Inputs

To let the player control the game piece with the arrow keys, we will have to add a variable to track which keys the player is pressing. Declare a variable called keyInputs below where we declared gamePieces. Declaring it there will let all of the functions access the new variable.

        var gamePiece;
var keyInputs;

The keyInput variable should be initialized when the game is created in the create function.

        function create(){
  gamePiece = this.physics.add.sprite(270, 450, 'gamePiece');
  keyInputs = this.input.keyboard.createCursorKeys();
}

Now in the update function, we can check if the player is pressing an arrow key, and if they are, move our game piece accordingly. In the example below, the game piece is moved 2px, but you can make that a larger or smaller number. Moving the piece 1px at a time seemed a little slow.

        function update(){
  if(keyInputs.left.isDown){
    gamePiece.x = gamePiece.x - 2;
  }
  if(keyInputs.right.isDown){
    gamePiece.x = gamePiece.x + 2;
  }
  if(keyInputs.up.isDown){
    gamePiece.y = gamePiece.y - 2;
  }
  if(keyInputs.down.isDown){
    gamePiece.y = gamePiece.y + 2;
  }
}

The game has a moveable character now! But to truly be a game, we need an objective. Let's add some obstacles. Dodging obstacles was the basis for a lot of the games in the 8-bit era.

Adding Obstacles To The Game

This code example uses two obstacle sprites called obstacle1 and obstacle 2. obstacle1 is a blue square and obstacle2 is green. Each image will need to be preloaded just like the gamepiece sprite.

        function preload(){
  this.load.image('gamePiece', 'img/gamePiece.png');
  this.load.image('obstacle1', 'img/obstacle1.png');
  this.load.image('obstacle2', 'img/obstacle2.png');
}

Then each obstacle sprite will need to be initialized in the create function, just like the gamepiece.

        function create(){
  gamePiece = this.physics.add.sprite(270, 450, 'gamePiece');
  keyInputs = this.input.keyboard.createCursorKeys();
  obstacle1 = this.physics.add.sprite(200, 0, 'obstacle1');
  obstacle2 = this.physics.add.sprite(0, 200, 'obstacle2');
}

Making The Obstacles Move

To move the pieces this time, we don't want to use player input. Instead, let's have one piece move from the top to the bottom and the other move left to right. To do that, add the following code to the update function:

        obstacle1.y = obstacle1.y + 4;
if(obstacle1.y > 600){
  obstacle1.y = 0;
  obstacle1.x = Phaser.Math.Between(0, 600);
}
 
obstacle2.x = obstacle2.x + 4;
if(obstacle2.x > 600){
  obstacle2.x = 0;
  obstacle2.y = Phaser.Math.Between(0, 600);
}

The code above will move obstacle1 down the screen and obstacle2 across the game area 4px each frame. Once a square is off screen, it is moved back to the opposite side at a new random spot. This will ensure that there is always a new obstacle for the player.

phaser game without collision detection

Detecting Collisions

But we are not quite done yet. You might have noticed that our player can pass right through the obstacles. We need to make the game detect when the player hits an obstacle and end the game.

The Phaser physics library has a collider detector. All we need to do is initialize it in the create function.

        this.physics.add.collider(gamePiece, obstacle1, function(gamePiece, obstacle1){
  gamePiece.destroy();
  obstacle.destroy();
  obstacle2.destroy();
});
this.physics.add.collider(gamePiece, obstacle2, function(gamePiece, obstacle2){
  gamePiece.destroy();
  obstacle.destroy();
  obstacle2.destroy();
});

The collider method requires three parameters. The first two parameters identify which objects are colliding. So above, we have two colliders set up. The first detects when the gamepiece collides with obstacle1 and the second collider is looking for collisions between the gamepiece and obstacle2.

The third parameter tells the collider what to do once it detects a collision. In this example, there is a function. If there is a collision, all the game elements are destroyed; this stops the game. Now the player will gameover if they hit an obstacle.

Give Game Development a Try With Phaser

There are many different ways that this game can be improved and made more complex. We have only created one player, but a second playable character could be added and controlled with the "awsd" controls. Similarly, you could experiment with adding more obstacles and varying the speed of their movement.

This introduction will get you started, but there is plenty more left to learn. The great thing about Phaser is that a lot of the game physics is done for you. It is a great easy way to get started designing 2D games. Continue to build on this code and refine your game.

If you run into any errors, your browser debugger is a great way to discover the issue.