11th Dec 2013
This tutorial is a follow-up to the TypeScript with Phaser beginners guide. I will assume you have worked through that tutorial already and have a working set-up in which you can compile Phaser projects. From this base we will expand on the simple approach taken in the beginners guide and show how to structure a more advanced project that benefits from the power of TypeScript.
Create a new Project
In the first tutorial everything was hanging off a single
app.tsfile with one bundled class. This time around we’re going to break it up into more individual classes. In Visual Studio create a new empty TypeScript project, then add the phaser TypeScript definition and JS library files to it as outlined in Step 2 in the first tutorial.
Download this asset pack and unzip it into the project folder. We’ll reference these files in our code.
Create a new TypeScript file called
Here we have created a new Module called
Castlevaniaunder which all of our game classes will live. Obviously you’d change this to whatever your game is actually called, unless you’re genuinely working on a Castlevania game, in which case I’m eternally jealous
Gameclass is extending
Phaser.Game. As a result we need to call super in the constructor and pass in our game settings. Once done we add 4 States to the game: Boot, Preloader, MainMenu and Level1, and then start the Boot state. You don’t have to add ALL of the States at this point, but there is no harm in doing so.
10th Dec 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”.
After a short while it will create the Solution and open a file called
app.tscontaining the default TypeScript Greeter class example:
7th Dec 2013
This article was written by Alvin Ourrad and Richard Davey.
Freshly updated for Phaser 2.0!
Welcome to the our first tutorial on Making a Game with Phaser. Here we will learn how to create a small game involving a player running and jumping around platforms collecting stars. While going through this process we’ll explain some of the core features of the framework.
What is Phaser?
Phaser is an HTML5 game framework which aims to help developers make powerful, cross-browser HTML5 games really quickly and, unlike some others, has solely been built to work with the mobile browsers. The only browser requirement is the support of the canvas tag. It also borrows a lot from Flixel.
- Download the source files and assets that go with this tutorial.
- Also make sure you go through the Getting Started Guide, it will show you how to download the framework, set up a local development environment, and give you a glimpse of the structure of a Phaser project and its core functions.
If you’ve gone through the Getting Started Guide you will have downloaded Phaser and got everything set-up and ready to code. Download the resources for this tutorial from here and unzip it into your web root.
Line 1 is where you bring Phaser to life by creating an instance of a Phaser.Game object and assigning it to a local variable called ‘game’. Calling it ‘game’ is a common practice, but not a requirement, and this is what you will find in the Phaser examples.
The first two parameters are the width and the height of the canvas element that Phaser will create. In this case 800 x 600 pixels. Your game world can be any size you like, but this is the resolution the game will display in. The third parameter can be either Phaser.CANVAS, Phaser.WEBGL, or Phaser.AUTO. This is the rendering context that you want to use. The recommended parameter is Phaser.AUTO which automatically tries to use WebGL, but if the browser or device doesn’t support it it’ll fall back to Canvas.
The fourth parameter is an empty string, this is the id of the DOM element in which you would like to insert the canvas element that Phaser creates. As we’ve left it blank it will simply be appended to the body. The final parameter is an object containing four references to Phasers essential functions. Their use is thoroughly explained here. Note that this object isn’t required – Phaser supports a full State system allowing you to break your code into much cleaner single objects. But for a simple Getting Started guide such as this we’ll use this approach as it allows for faster prototyping.
Let’s load the assets we need for our game. You do this by putting calls to game.load inside of a function called preload. Phaser will automatically look for this function when it starts and load anything defined within it.
Create a Sprite
If you bring up the page in a browser you should now see a black game screen with a single star sprite in the top left corner:
The order in which items are rendered in the display matches the order in which you create them. So if you wish to place a background behind the star sprite you would need to ensure that it was added as a sprite first, before the star.
Under the hood game.add.sprite is creating a new Phaser.Sprite object and adding the sprite to the “game world”. This world is where all your objects live, it can be compared to the Stage in Actionscript3.
Note: The game world has no fixed size and extends infinitely in all directions, with 0,0 being the center of it. For convenience Phaser places 0,0 at the top left of your game for you, but by using the built-in Camera you can move around as needed.
The world class can be accessed via game.world and comes with a lot of handy methods and properties to help you distribute your objects inside the world. It includes some simple properties like game.world.height, but also some more advanced ones that we will use in another tutorial.
If you run this, which you’ll find as part4.html in the tutorial zip file, you should see a much more game-like scene:
The first part is the same as the star sprite we had before, only instead we changed the key to ‘sky’ and it has displayed our sky background instead. This is an 800×600 PNG that fills the game screen.
As with sprites game.add creates our Group object. We assign it to a new local variable called platforms. Now created we can add objects to it. First up is the ground. This is positioned at the bottom of the game and uses the ‘ground’ image loaded earlier. The ground is scaled to fill the width of the game. Finally we set its ‘immovable’ property to true. Had we not done this the ground would move when the player collides with it (more on this in the Physics section).
With the ground in place we create two smaller ledges to jump on to using the exact same technique as for the ground.
Ready Player One
This creates a new sprite called ‘player’, positioned at 32 pixels by 150 pixels from the bottom of the game. We’re telling it to use the ‘dude’ asset previously loaded. If you glance back to the preload function you’ll see that ‘dude’ was loaded as a sprite sheet, not an image. That is because it contains animation frames. This is what the full sprite sheet looks like:
You can see 9 frames in total, 4 for running left, 1 for facing the camera and 4 for running right. Note: Phaser supports flipping sprites to save on animation frames, but for the sake of this tutorial we’ll keep it old school. We define two animations called ‘left’ and ‘right’. The ‘left’ animation uses frames 0, 1, 2 and 3 and runs at 10 frames per second. The ‘true’ parameter tells the animation to loop. This is our standard run-cycle and we repeat it for running in the opposite direction. With the animations set we create a few physics properties.
The Body and Velocity: A world of physics
Phaser has support for a variety of different physics systems. It ships with Arcade Physics, Ninja Physics and P2.JS Full-Body Physics. For the sake of this tutorial we will be using the Arcade Physics system, which is simple and light-weight, perfect for mobile browsers. You’ll notice in the code that we have to start the physics system running, and then for every sprite or Group that we wish to use physics on we enable them.
This is an arbitrary value, but logically, the higher the value, the heavier your object feels and the quicker it falls. If you add this to your code or run part5.html you will see that the player falls down without stopping, completely ignoring the ground we created earlier:
The reason for this is that we’re not yet testing for collision between the ground and the player. We already told Phaser that our ground and ledges would be immovable. Had we not done that when the player collided with them it would stop for a moment and then everything would have collapsed. This is because unless told otherwise, the ground sprite is a moving physical object (also known as a dynamic body) and when the player hits it, the resulting force of the collision is applied to the ground, therefore, the two bodies exchange their velocities and ground starts falling as well.
The update function is called by the core game loop every frame. The Physics.collide function is the one that performs the magic. It takes two objects and tests for collision and performs separation against them. In this case we’re giving it the player sprite and the platforms Group. It’s clever enough to run collision against all Group members, so this one call will collide against the ground and both ledges. The result is a firm platform:
Controlling the player with the keyboard
Although we’ve added a lot of code it should all be pretty readable. The first thing we do is reset the horizontal velocity on the sprite. Then we check to see if the left cursor key is held down. If it is we apply a negative horizontal velocity and start the ‘left’ running animation. If they are holding down ‘right’ instead we literally do the opposite. By clearing the velocity and setting it in this manner, every frame, it creates a ‘stop-start’ style of movement.
The player sprite will move only when a key is held down and stop immediately they are not. Phaser also allows you to create more complex motions, with momentum and acceleration, but this gives us the effect we need for this game. The final part of the key check sets the frame to 4 if no keyis held down. Frame 4 in the sprite sheet is the one of the player looking at you, idle.
Jump to it
The final part of the code adds the ability to jump. The up cursor is our jump key and we test if that is down. However we also test if the player is touching the floor, otherwise they could jump while in mid-air. If both of these conditions are met we apply a vertical velocity of 350 px/sec sq. The player will fall to the ground automatically because of the gravity value we applied to it. With the controls in place we now have a game world we can explore. Load up part7.html and have a play. Try tweaking values like the 350 for the jump to lower and higher values to see the effect it will have.
Quite simply the star is killed, which removes it from display. Running the game now gives us a player that can dash about, jumping, bouncing off the platforms and collecting the stars that fall from above. Not bad for a few lines of hopefully mostly quite readable code
So 10 points are added for every star and the scoreText is updated to show this new total. If you run part9.html you will see the final game.
You have now learnt how to create a sprite with physics properties, to control its motion and to make it interact with other objects in a small game world. There are lots more things you can do to enhance this, for example there is no sense of completion or jeopardy yet. Why not add some spikes you must avoid? You could create a new ‘spikes’ group and check for collision vs. the player, only instead of killing the spike sprite you kill the player instead. Or for a non-violent style game you could make it a speed-run and simply challenge them to collect the stars as quickly as possible. We’ve included a few
extra graphics in the zip file to help inspire you.
With the help of what you have learnt in this tutorial and the 250+ examples available to you, you should now have a solid foundation for a future project. But as always if you have questions, need advice or want to share what you’ve been working on then feel free to ask for help in the Phaser forum.
More tutorials will follow, stay tuned
1st Dec 2013
I’m pleased to say that version 1.1.3 of Phaser is now released! And we’ve also got over 1000 stars on our github project, which is excellent
This release focused on updating Phaser to use the latest version of Pixi.js, which introduces the wonderful world of shaders to your WebGL games. We have been busy creating and modifying shaders for your use and you’ll find a bunch of them in the new filters folder in the repository plus examples in the Examples area. They include fire, plasma, light beams, marble, blur effects and there are lots more coming. It’s safe to say we’re a little bit addicted to creating shaders at the moment. They can add a visual sheen to 2D games that transport it to another level entirely. Don’t worry though, we haven’t bloated out the core library: we allow you to load them dynamically as needed.
There is also a brand new (but still experimental) BitmapData object which we’ll work on making more solid over the coming weeks. But it essentially gives you a blank canvas onto which you can draw, plot lines, render text, copy and paste pixels and perform all kinds of effects. It is designed to be used as a texture by any Sprite. So multiple sprites can share the same dynamic texture now. We’ll carry on ironing out this class in future releases, but it’s already pretty powerful.
I have spent a long time updating the documentation as well. Some classes which didn’t have any, like the Tilemap ones, are now fully done. And I’ve replaced lots of instances of place holder documentation with actual meaningful descriptions, with many type definitions have also fixed. Thanks to community help the TypeScript definitions file is now a lot more accurate too.
There is a brand new Getting Started guide on the Phaser site and we will start releasing new tutorials in the coming weeks too.
Marching towards 1.1.4
We will aim to get version 1.1.4 (“Kandor”) released before the end of the year, and then start planning out the features that will form the backbone of the 1.2 release. Right now we’re almost certain that will consist of a proper physics system, as our p2.js tests have been going extremely well.
It never ceases to amaze me just how receptive the community has been to Phaser. Every day we’re seeing more and more games created in it, new developers signing-up to the forum and some fantastic contributions via github, both in the shape of reported issues, fixes and enhancements. Not a day goes by when something isn’t improved or planned, helping us take it that little bit further with each step. I’m genuinely excited about what 2014 will bring.
7th Nov 2013
I’m happy to say that I’ll be speaking at the Montreal International Games Summit this year. My session is called HTML5 Game Development In-depth and is on November 11th from 2.45pm – 3.45pm in Room 520B. Here is the link for your MIGS planner.
This will be my first time attending MIGS. Actually, it will be my first time in Canada, and I’m really looking forward to it.
Usually I tend to be asked to present “beginner” level HTML5 development sessions. But this time they specifically asked me to avoid the “why?” side of things and just dive right in to the “How”.
So I’ll be looking at the different platforms involved (yes, there is more than one :)), the technology choices, the libraries and frameworks that help solve specific issues and some common pitfalls to avoid. I’m not going to delve into just one framework in depth, as I feel that will narrow what you’ll get out of the session. So I won’t just stand there going on about Phaser for an hour (sorry! I know some of you asked if I would :)). Instead I will use more of a shotgun approach, scattering you with a collection of tools and suggestions on when to use them.
My hope is that you can walk away from my session with at least a bunch of new github repos to claw down and experiment with, and hopefully a deeper understanding of the processes involved in HTML5 game creation – and fundamentally how the destination platform dictates which processes are needed.
If you’re going to be attending MIGS 10 and would like to meet-up then please either come and see me after my session or grab me on twitter.
All about Photon Storm and our
HTML5 game development services
Filter our Content
- Cool Links
- Flash Game Dev Tips
- Game Development
- Geek Shopping
- In the Media
- Phaser 3