Phaser for Beginners

The structure of your Phaser project

Every HTML5 game is a web page with some magic in it, so that’s what we are going to do: the creation of a web page in a folder placed inside our local web server. Without forgetting to include Phaser framework! Inside build folder in the zipped package you just downloaded, you will find phaser.js file. That’s the only Phaser file we will need during the development of our game. Create an index.html file which will be the web page you will call to launch the game, and you’ll have all you need to start writing the first lines of code of your first Phaser game. Your project folder now should contain two files.

If you followed all instructions, your folder structure will look like this:

Now let’s edit index.html :

As you can see, it’s just an empty web page with only a call to two JavaScript files: phaser.js is the file we just downloaded, and game.js will contain our game script. This is the time to create a new file in the same folder, call it game.js and write this code:

Congratulations, you just created your first Phaser script. You can use this first script as a starting template file for your future projects too.

Let’s see what these lines mean:

window.onload is fired at the end of the document loading process, in our case when all scripts called in index.html have finished loading. This means everything is ready to be executed, so we can run the function.

A JavaScript function is a block of code designed to perform a particular task, executed when “something” invokes it. When you make something to execute a function, we say you call the function.

Inside the function there’s only one line:

This is where everything begins.

A function can contain any number of lines, and we use curly brackets, { and } to define the start and the end of a function, or more in general, the start and the end of a block of code.

Game object will be the game itself. The two numbers inside the parentheses represent respectively the width and the height of the game, in pixels. Game object is assigned to a variable called game.

A JavaScript variable is a container for storing data values. When you create a variable we say you declare a variable, using the var keyword. You assign a value to a variable with = operator.

Translating what we done in English, it means “once the entire document has been loaded, create a new Game object with a width and height of 500 pixels and assign it to a variable called game .

A JavaScript object is a particular kind of variable which can contain many values.

Well, this is our first Phaser game, so let’s run it and see what happens.


Next Tutorial →

Running your game

← Previous Tutorial

Choosing a editor, server and browser

Leave a Reply

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