How to use Phaser with TypeScript

Published on 10th December 2013

In this tutorial we'll cover setting-up a Phaser TypeScript project. We're going to specifically cover using Visual Studio, but the concepts will be similar regardless of which IDE you're using. This guide is based on TypeScript 0.9.5 and Visual Studio 2013. Ensure you have both of these installed before carrying on, as it probably won't work with earlier builds of TypeScript. You will also need a local copy of the Phaser repository. See the Phaser Getting Started Guide for details on how to download this.

Step 1: Create a New Project

In Visual Studio create a new Project. Make sure you pick "HTML Application built with TypeScript" as the Template, which can be found under the TypeScript template category on the left. We've called our sample project "PhaserTypeScript". part1

After a short while it will create the Solution and open a file called app.ts containing the default TypeScript Greeter class example:

[part2../../images/2013/12/part2.png]

Step 2: Add the Phaser files to the Project

The first thing we need to do is add the Phaser build files and TypeScript definitions file into the Project.  To do this select "Add Existing Item" from the "Project" menu in Visual Studio (or press Shift + Alt + A). It will open a standard Windows File Explorer. Browse to the Phaser repository and within the build select the following 3 items: phaser.d.ts, phaser.js and phaser.min.js:

[part3../../images/2013/12/part31.png]

The files should all appear in the Solution Explorer window. Visual Studio has copied them from the Phaser repository over into the Project folder, so remember this if you ever update Phaser; it won't automatically update our Visual Studio projects too. In order to complete this part of the tutorial you'll also need to download this image file and save it to your Project folder. So it should be saved in the same place as default.htm, app.ts, and the other files.

Step 3: Edit default.htm

Double-click default.htm to open it and you'll see the standard boilerplate that the TypeScript template inserts:

<!DOCTYPE html>

<html lang="en"> <head> <meta charset="utf-8" /> <title>TypeScript HTML App</title> <link rel="stylesheet" href="app.css" type="text/css" /> <script src="app.js"></script> </head> <body> <h1>TypeScript HTML App</h1>

<div id="content"></div>

</body> </html>

We need to add Phaser into this, so before the app.js line add:

<script src="phaser.js"></script>

You'll notice there is a div tag in the html already with an id of content. We'll use this to hook our game to. Save your changes.

Step 4: Edit app.ts

It's nice of the TypeScript template to have given us the sample Greeter code in app.ts, but we don't need any of it, so remove it all and replace it with the following:

class SimpleGame {

    constructor() {
        this.game = new Phaser.Game(800, 600, Phaser.AUTO, 'content', { preload: this.preload, create: this.create });
    }

    game: Phaser.Game;

    preload() {
        this.game.load.image('logo', 'phaser2.png');
    }

    create() {
        var logo = this.game.add.sprite(this.game.world.centerX, this.game.world.centerY, 'logo');
        logo.anchor.setTo(0.5, 0.5);
    }

}

window.onload = () => {

    var game = new SimpleGame();

};

Save this, it's time to test it.

Step 5: Test your 'game'

It's time to test our game out. To do this either press F5 (Start Debugging) or click the green play arrow next to your browser of choice on the top menu:

[part4../../images/2013/12/part41.png]

After a brief compilation step, Chrome or your default browser should open displaying our test game:

[part5../../images/2013/12/part51.png]

You'll notice it has connected to localhost on port 5407. Visual Studio selects a port at random, so if your page loads on a different port then don't worry. Hopefully if you've got the paths correct and copied the files over then you'll see a Phaser logo displayed in the middle of your game. If you received errors about being unable to find Phaser then it's possible you may need to directly reference the definitions file in your code. If so, add this as the top line of app.ts:

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

Now let's return to our project. First close the browser window it opened and then swap back to Visual Studio. You'll notice that it's got an orange glow around it because it's running in Debug mode:

[part6../../images/2013/12/part61.png]

Click the red stop icon to end Debug mode (or press Shift + F5).

Step 6: The power of Code Completion

So far, so good. Now let's scale the sprite in size, which will help demonstrate a powerful feature of using Phaser within TypeScript: code completion. Back in app.ts, after the line:

logo.anchor.setTo(0.5, 0.5);

Start a new line and type in logo. - upon entering the period character you should see a pop-up menu showing all of the properties you can explore within a Phaser.Sprite object: part7 Select scale from the pop-up list. It will fill the code in for you. Now press period again and a second pop-up menu will appear, showing all the properties that scale has: part8 Pick setTo from the list and enter an opening brace: ( - this will trigger the final part of code-completion, the parameters list: part9 By looking at this you know that the setTo method expects two number values. We can now complete our line of code safe in the knowledge we're giving it what the compiler (and Phaser) expects:

logo.scale.setTo(0.2, 0.2);

If you press F5 you should see a tiny scrunched-up logo in the middle of your game. Using this same process enter the following line of code after the scale call:

this.game.add.tween(logo.scale).to({ x: 1, y: 1 }, 2000, Phaser.Easing.Bounce.Out, true);

The final create function should now look like this (we've added a few line-breaks for readability):

    create() {

        var logo = this.game.add.sprite(this.game.world.centerX, this.game.world.centerY, 'logo');

        logo.anchor.setTo(0.5, 0.5);
        logo.scale.setTo(0.2, 0.2);

        this.game.add.tween(logo.scale).to({ x: 1, y: 1 }, 2000, Phaser.Easing.Bounce.Out, true);
    }

Press F5 and the logo will now bounce into the screen, wobbling for a few seconds before settling down.

A note about the Phaser TypeScript definitions file

We originally used an automated process to generate our TypeScript definitions file from the core JavaScript source code. However we found this introduced lots of data-type errors and we've been methodically patching them by hand since then. You are very likely to find there are some functions or properties that exist in Phaser that are not in the definitions file. Equally some method signatures may be incorrect too. If you come across any please report them and we'll fix them as a matter of urgency. If you find an error is holding back your project you can always edit the phaser.d.ts file in any text editor and correct the part that is wrong.

Next Steps

This has served as a basic introduction to using Phaser with TypeScript. The next article in the series is Advanced TypeScript Project Structures. This covers using TypeScript features to extend Phaser classes and our approach for a project structure. Don't forget to subscribe to our Phaser newsletter for details.

In this tutorial we'll cover setting-up a Phaser TypeScript project. We're going to specifically cover using Visual Studio, but the concepts will be similar regardless of which IDE you're using. This guide is based on TypeScript 0.9.5 and Visual Studio 2013. Ensure you have both of these installed before carrying on, as it probably won't work with earlier builds of TypeScript. You will also need a local copy of the Phaser repository. See the Phaser Getting Started Guide for details on how to download this.

Step 1: Create a New Project

In Visual Studio create a new Project. Make sure you pick "HTML Application built with TypeScript" as the Template, which can be found under the TypeScript template category on the left. We've called our sample project "PhaserTypeScript". part1

After a short while it will create the Solution and open a file called app.ts containing the default TypeScript Greeter class example:

[part2../../images/2013/12/part2.png]

Step 2: Add the Phaser files to the Project

The first thing we need to do is add the Phaser build files and TypeScript definitions file into the Project.  To do this select "Add Existing Item" from the "Project" menu in Visual Studio (or press Shift + Alt + A). It will open a standard Windows File Explorer. Browse to the Phaser repository and within the build select the following 3 items: phaser.d.ts, phaser.js and phaser.min.js:

[part3../../images/2013/12/part31.png]

The files should all appear in the Solution Explorer window. Visual Studio has copied them from the Phaser repository over into the Project folder, so remember this if you ever update Phaser; it won't automatically update our Visual Studio projects too. In order to complete this part of the tutorial you'll also need to download this image file and save it to your Project folder. So it should be saved in the same place as default.htm, app.ts, and the other files.

Step 3: Edit default.htm

Double-click default.htm to open it and you'll see the standard boilerplate that the TypeScript template inserts:

<!DOCTYPE html>

<html lang="en"> <head> <meta charset="utf-8" /> <title>TypeScript HTML App</title> <link rel="stylesheet" href="app.css" type="text/css" /> <script src="app.js"></script> </head> <body> <h1>TypeScript HTML App</h1>

<div id="content"></div>

</body> </html>

We need to add Phaser into this, so before the app.js line add:

<script src="phaser.js"></script>

You'll notice there is a div tag in the html already with an id of content. We'll use this to hook our game to. Save your changes.

Step 4: Edit app.ts

It's nice of the TypeScript template to have given us the sample Greeter code in app.ts, but we don't need any of it, so remove it all and replace it with the following:

class SimpleGame {

    constructor() {
        this.game = new Phaser.Game(800, 600, Phaser.AUTO, 'content', { preload: this.preload, create: this.create });
    }

    game: Phaser.Game;

    preload() {
        this.game.load.image('logo', 'phaser2.png');
    }

    create() {
        var logo = this.game.add.sprite(this.game.world.centerX, this.game.world.centerY, 'logo');
        logo.anchor.setTo(0.5, 0.5);
    }

}

window.onload = () => {

    var game = new SimpleGame();

};

Save this, it's time to test it.

Step 5: Test your 'game'

It's time to test our game out. To do this either press F5 (Start Debugging) or click the green play arrow next to your browser of choice on the top menu:

[part4../../images/2013/12/part41.png]

After a brief compilation step, Chrome or your default browser should open displaying our test game:

[part5../../images/2013/12/part51.png]

You'll notice it has connected to localhost on port 5407. Visual Studio selects a port at random, so if your page loads on a different port then don't worry. Hopefully if you've got the paths correct and copied the files over then you'll see a Phaser logo displayed in the middle of your game. If you received errors about being unable to find Phaser then it's possible you may need to directly reference the definitions file in your code. If so, add this as the top line of app.ts:

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

Now let's return to our project. First close the browser window it opened and then swap back to Visual Studio. You'll notice that it's got an orange glow around it because it's running in Debug mode:

[part6../../images/2013/12/part61.png]

Click the red stop icon to end Debug mode (or press Shift + F5).

Step 6: The power of Code Completion

So far, so good. Now let's scale the sprite in size, which will help demonstrate a powerful feature of using Phaser within TypeScript: code completion. Back in app.ts, after the line:

logo.anchor.setTo(0.5, 0.5);

Start a new line and type in logo. - upon entering the period character you should see a pop-up menu showing all of the properties you can explore within a Phaser.Sprite object: part7 Select scale from the pop-up list. It will fill the code in for you. Now press period again and a second pop-up menu will appear, showing all the properties that scale has: part8 Pick setTo from the list and enter an opening brace: ( - this will trigger the final part of code-completion, the parameters list: part9 By looking at this you know that the setTo method expects two number values. We can now complete our line of code safe in the knowledge we're giving it what the compiler (and Phaser) expects:

logo.scale.setTo(0.2, 0.2);

If you press F5 you should see a tiny scrunched-up logo in the middle of your game. Using this same process enter the following line of code after the scale call:

this.game.add.tween(logo.scale).to({ x: 1, y: 1 }, 2000, Phaser.Easing.Bounce.Out, true);

The final create function should now look like this (we've added a few line-breaks for readability):

    create() {

        var logo = this.game.add.sprite(this.game.world.centerX, this.game.world.centerY, 'logo');

        logo.anchor.setTo(0.5, 0.5);
        logo.scale.setTo(0.2, 0.2);

        this.game.add.tween(logo.scale).to({ x: 1, y: 1 }, 2000, Phaser.Easing.Bounce.Out, true);
    }

Press F5 and the logo will now bounce into the screen, wobbling for a few seconds before settling down.

A note about the Phaser TypeScript definitions file

We originally used an automated process to generate our TypeScript definitions file from the core JavaScript source code. However we found this introduced lots of data-type errors and we've been methodically patching them by hand since then. You are very likely to find there are some functions or properties that exist in Phaser that are not in the definitions file. Equally some method signatures may be incorrect too. If you come across any please report them and we'll fix them as a matter of urgency. If you find an error is holding back your project you can always edit the phaser.d.ts file in any text editor and correct the part that is wrong.

Next Steps

This has served as a basic introduction to using Phaser with TypeScript. The next article in the series is Advanced TypeScript Project Structures. This covers using TypeScript features to extend Phaser classes and our approach for a project structure. Don't forget to subscribe to our Phaser newsletter for details.