No results found

Try a different or more specific query
Developer Console
Appstore Blogs

Appstore Blogs

Want the latest?

appstore topics

Recent Posts

Archive

Showing posts tagged with Phaser

July 23, 2014

Jesse Freeman

Welcome to part 3 and the final installment, of my Introduction to Phaser. In the first post, we configured our dev environment as well as the code we’ll need to run Phaser itself. In the second post, we covered preloading, displaying sprites and setting up the game modes. If you missed the two tutorials, please go back and follow those steps before moving on. In this tutorial we are going to cover the following:

  • Building A Wall
  • Spawning Walls
  • Debugging Walls
  • Handling Collision Detection
  • Adding Score
  • Adding Sounds

Let’s get started.

Building A Wall

Right now our game isn’t very fun or challenging. To help with this we’ll add walls with a small gap in the middle for our player to fly through. To get started, we’ll need to create two functions: one to spawn a wall and the other to put two walls together with the gap for the player to fly through.

Step 1. Add the following method to our state object:

spawnWall: function(y, flipped){

}

This function accepts the y position for the wall and if it needs to be flipped vertically. This is important since we will be using the same wall graphic for our top and bottom wall sprites. We’ll need a way to group them together into a single manageable game object.

Step 2. In our create() method, right under where we setup the background TileSprite we should add our wall group:

create: function(){
    this.background = this.add.tileSprite(0,0, this.world.width, this.world.height, 'background');

    this.walls = this.add.group();

It’s important to create this after our background so it shows up on top. Now we’ll be able to access each of the wall sprites in our game from a single group which we are calling walls. This will make a little more sense later on when we add in collision.

Step 3. Add the following to our spawnWall() method:

spawnWall: function(y, flipped){
    var wall = this.walls.create(
        game.width,
        y + (flipped ? -OPENING : OPENING) / 2,
        'wall'
    )
}

This adds a new wall sprite to our walls group. The staring x position is set to the width of the game so it starts off-screen and we also use the supplied flipped value to detect if the wall going to be displayed on the top or the bottom. To do this we take advantage of something called a Ternary Operator. Basically the way that this works is we have a condition to the left of the question mark and then the value if true followed by the value if the condition is false. Here is a representation of this:

condition ? true : false;

Step 4. Add the following constant to the top of our script:

var OPENING = 200;

Step 5. Add a few more lines of code to our spawnWall() function:

this.physics.arcade.enableBody(wall);
wall.body.allowGravity = false;
wall.scored = false;
wall.body.immovable = true;
wall.body.velocity.x = -SPEED;
if(flipped){
    wall.scale.y = -1;
    wall.body.offset.y = -wall.body.height;
}

This disables gravity for the wall.  Then, we set the y scale to -1 if it’s flipped, or 1 if it is staying the same. We also need to adjust the y offset value of the body if the wall is flipped to account for the scale change we made on the previous line. Finally we set the velocity.x of the wall to our SPEED constant. You’ll notice we make this value negative. That way it moves to the left of the screen giving the impression that the player is flying past it.

Step 6. Add the following line to the end of the spawnWall() function:

return wall;

This will allow us to get a reference to the wall instance being created every time we call the spawnWall() method. We need to test if this works, but we’ll need to add a little bit of debug code first.

Step 7. Add the following line of code to our create method:

this.spawnWall(300);

Step 8. Refresh the game in your browser and now you should see your first wall fly by below the player:

Step 9. To test creating a wall on the top of the screen, simply modify the wallSpawn() function to look like this:

this.spawnWall(300, true);

Step 10. With true being passed into wallSpawn() you can refresh the game to see the new wall on the top of the screen:

Spawning Walls

At this point we have the foundation in place for us to spawn the walls in our game. We’ll create a method to generate both a top and bottom wall as well as connect it up to a timer.

Step 1. Before moving on, make sure you comment out the spawn code we used to test with in the previous section:

//this.spawnWall(300, true);

Step 2. Now add new method called spawnWalls() with the following:

spawnWalls: function(){
    var wallY = this.rnd.integerInRange(game.height *.3, game.height *.7);
    var botWall = this.spawnWall(wallY);
    var topWall = this.spawnWall(wallY, true);
}

Take note that we added a s to this function’s name since our spawnWall() function only generates a single instance. In the spawnWalls() function we are taking advantage of Phaser’s RandomDataGenerator class. You can access it from the game object by calling this.rnd. This utility has a lot of useful methods for helping create random values in your game. We’ll be taking advantage of integerInRange() which requires a minimum and maximum value to return something in-between the two. Finally to keep the walls within the screen area we calculate the “safe” zone were we would want our walls to spawn by taking a percentage from the top and bottom of the visible area.

Step 3. Now we are ready to start a timer to spawn new walls. In our start() function, add the following code:

this.wallTimer = this.game.time.events.loop(Phaser.Timer.SECOND * SPAWN_RATE, this.spawnWalls, this);
this.wallTimer.timer.start();

Step 4. We’ll also need to add a new constant at the top of our script:

var SPAWN_RATE = 1.25; 

Step 5. Refresh your browser and you can now fly through an endless supply of walls being randomly generated at a set interval.

Debugging Walls

Everything is looking good but there is just one minor issue. While you may not see it, the walls that have moved off the screen are still in the game. We need to do a little bit of cleanup to make sure that we destroy any wall that is no longer visible.

Step 1. Add the following code to our update function right after we test if player is out of bounds:

if (this.player.body.bottom >= this.world.bounds.bottom) {
    this.setGameOver();
}

this.walls.forEachAlive(function (wall) {
    if (wall.x + wall.width < game.world.bounds.left) {
        wall.kill();
    }
})

Remember back to when we set up our walls in the group? This forEachAlive loop allows us to easily iterate through all the wall instances inside of that group still active in the game. From there we setup a generic function to test if the instance’s x position is greater than the game world’s bounds.left value so we can destroy it. Calling kill() on an instance completely removes it from the game and from memory as well. Without this function, the game would have a memory leak which would cause performance issues and a poor user experience. Phaser also has some really great pooling classes but for this intro level tutorial we’ll just do this manually. The game is simple enough not to worry about the extra overhead we incur by creating new wall instances from scratch.

Step 2. In the reset() function of our state object add the following line:

this.walls.removeAll();

This ensures we get a clean slate when starting the game over. And while we are on the topic of starting over, you may have noticed that the walls still scroll by when the game is over?

Step 3. Next, we’ll need to stop the walls from moving when we end the game. Add the following to our setGameOver() function:

this.walls.forEachAlive(function (wall) {
    wall.body.velocity.x = wall.body.velocity.y = 0;
});

this.wallTimer.timer.stop();

This function will iterate through each wall instance and set the velocity.x to 0 to stop it from moving. We also stop the wallTimer to make sure nothing else gets created while the game is over.

Step 4. Run the game and make sure that the walls stop when game over before continuing on.

Handling Collision Detection

Now that we have walls, we can define what happens when a player hits a wall. Luckily for us, collision detection is really easy to implement in Phaser.

Step 1. To get started we’ll need a way to detect the actual collision. To do this, we add one line of code to our update function right after where we test if the player hits the bottom of the screen:

if(!this.gameOver){
    if(this.player.body.bottom >= this.world.bounds.bottom){
        this.setGameOver();
    }
    this.physics.arcade.collide(this.player, this.walls, this.setGameOver, null, this);
}

This tells the physics engine to test for any collisions between two game objects or in this case a single object, the player, and the walls group. The next parameter is the callback the collision check should trigger if an overlap is detected.  Finally, we need to pass the game’s scope to the callback parameter.

Step 2. At this point, everything else is already setup for us to build the game over state. Now if you test the game, you’ll see the game ends when the player touches the walls.

Step 3. When a collision occurs you may notice that the player actually bounces back. Add the following to the setGameOver() function to fix that:

this.player.body.velocity.x = 0;

Step 4. Run game and you’ll see the player no longer bounced back because we set the velocity.x to 0 when the game is over.

Adding Score

In this section, we learn how to add a function that increases the score when a player flies through the walls. To get started, we are going to need a way to determine if the player has flown past a wall, and then give them a score for it.

Step 1. We’ll need to add a new function called addScore() to handle the collision callback:

addScore: function (wall) {
    wall.scored = true;
    this.score += .5;
    this.scoreText.setText("SCORE\n" + this.score);
}

Here you can see we are getting a reference to a wall instance, adding a score and updating the score text. One thing to keep in mind is that since we have 2 instances, a top and bottom, that make up a single wall we only add half a point to the score. As the player flies past each wall section they will add up to a single value of 1 and the player will not even notice.

Step 2. Now we need to add in the logic to call addScore(). In the forEachAlive loop within the update() function, add the following:

this.walls.forEachAlive(function (wall) {
    if (wall.x + wall.width < game.world.bounds.left) {
        wall.kill();
    } else if(!wall.scored && wall.x <= state.player.x){
    		state.addScore(wall);
	}
})

Step 3.  Now you can refresh the browser and as you fly through each section of wall you’ll see the score increase by 1.

Adding Sounds

We now have a functional game. The only thing missing is fun – we need to add some sound effects to round out the playing experience.

Step 1. Before we can access any sound effects we’ll need to load them up. Add this to our preload method:

this.load.audio("jet", "/assets/jet.wav");
this.load.audio("score", "/assets/score.wav");
this.load.audio("hurt", "/assets/hurt.wav");

Step 2. Next we’ll create variables for each of our sound effects so we can access them easier. Add this to our create method:

this.jetSnd = this.add.audio('jet');
this.scoreSnd = this.add.audio('score');
this.hurtSnd = this.add.audio('hurt');

Step 3. Now it’s time to play our sound. In jet() function right after we set the player’s velocity.y to our jet constant add the following:

if(!this.gameOver){
    this.player.body.velocity.y = -JET;
    this.jetSnd.play();

Step 4. Now if you run the game and make the player fly, you should hear the sound. One thing to keep in mind is that each browser supports specific sound codecs. If you have any issues running the sound effects, make sure you are in Chrome or a browser that supports .wav playback.

Step 5. Next we’ll want to let the player know when they score.  To enable that, we need to add the following script to our addScore() function:

this.scoreSnd.play();

Step 6. Add this to the end of our setGameOver() method to let the player know when they hit a wall or go out of bounds:

this.hurtSnd.play();

Step 7. Now that we have the rest of our sound effects integrated, we can refresh the browser and test. You should now hear sounds when the player flies up, scores and dies.

Wrapping UP

At this point the game is basically done, and hopefully you’ve learned how some of the core mechanics of Phaser work.

To recap, we have covered importing assets, creating sprites, managing collision detection and playing sounds. There are a lot of really great resources out there to help you as you dig deeper into the Phaser framework. Make sure you check out the documentation as well as the samples included with the source code.  Also, feel free to take my existing codepen project and fork it to create your own variation of it.

One last thing I wanted to highlight is just how easy Amazon’s Web App tools are to use, helping to make publishing an online HTML5 game in the Amazon Appstore simple. I’ll be talking about how to take any HTML5 game and submit to the Amazon Appstore in a future post but the process couldn’t be easier. Here are the steps:

  1. Host your game online
  2. Download our Web App Tester to your Kindle Fire or Android device
  3. Put in the URL to your game to test that it works
  4. Sign up for free for an Amazon developer account and submit your game.

To learn more about the process, check out the documentation on our developer portal and the following reference links:

Related links:

- Jesse Freeman (@jessefreeman)

July 22, 2014

Jesse Freeman

Welcome to part two of my Introduction to Phaser. In the first part we configured our dev environment as well as the code we’ll need to run Phaser itself. If you missed the first tutorial, please go back and follow those steps before moving on. In this tutorial we are going to cover the following:

  • Preloading Assets
  • Displaying Images & Sprites
  • Building The Intro Loop
  • How to Start The Game
  • How to End The Game

Let’s get started.

Preloading Assets

Phaser has a built in preloader library. Over the course of this tutorial we will be loading in images, sprite sheets and audio files that will be accessible globally within to our game.

Step 1. If you are building your project locally with NodeJS or Apache you’ll need to copy over all of the assets (click here to download) and put them inside of the deploy folder like so:

You do not need to follow this step if you are using CodePen since the same files are being hosted online.

Step 2. Now let’s add the following to the empty preload function we created in our state object. The code bolded below represents what you need to actually add since we have already defined the preload function itself:

preload: function(){
    this.load.image("wall", "/assets/wall.png");
    this.load.image("background", "/assets/background-texture.png");
}

If you are using CodePen, you will need to preface the urls with http://games.jessefreeman.com/wp-content/public/workshop/phaser/ in order for this to correctly load. As an example, to load in the wall.png you will need the following URL:

http://games.jessefreeman.com/wp-content/public/workshop/phaser/assets/wall.png

Remember to do this for any external asset we preload in our game.

Before we move on, let’s talk about what is happening here. First, you’ll notice that we are calling Phaser’s built in game methods via the this scope. That’s because when our state is loaded up it assumes the same scope as the game object itself. This will allow us to call all of Phaser’s built in methods directly. Next, there are two parts to our load.image call, the unique id of the asset itself and the path to the asset so Phaser knows where to load it from.

Step 3. Now we will need to load in our player sprite sheet. Sprite sheets can be vertical, horizontal or even a grid. The only thing to keep in mind is that each sprite will need to be the exact same width and height in order for this to work correctly. This is what the sprite sheet looks like:

 

To correctly load this into our game we’ll need to add the following code below where we loaded the first two images:

this.load.spritesheet("player", "/assets/player.png", 48, 48);

This is similar to our load.image request except we have to define the width and height of the sprite. This allows Phaser to have the correct dimensions it needs to cut up our sprites into separate frames for animating later on. Phaser also supports loading texture atlases as well if you prefer to package all of your artwork into a single graphic but we will not be covering that in this tutorial.

Step 4. To test that this is working correctly, go back to your browser, refresh the page and inside of network connection debug tool you should now see that all of the game’s assets are loading correctly.

Now that we have our images, let’s look into how we can display them on the screen.

Displaying Images and Sprites

Adding images and sprites to the display is very easy in Phaser. To get started we are going to create our game’s background then make it scroll before adding in the player.

Step 1. Add the following to the create() function

this.background = this.add.tileSprite(0,0, this.world.width, this.world.height, 'background');

Here we are setting up a new background variable and assign it a TileSprite by calling this.add.tileSprite. The method requires x, y, width, height and label values. Since this texture will take up the entire screen, we are just going to set its x and y value to 0,0 and the width and height to the world’s width and height.

Step 2. Add the following constant to the top of our main.js file:

var SPEED = 200;

This SPEED value will now be a global in our game and help keep everything in sync.

Step 3. Now add the following code right below where we defined our background in the create() method:

this.background = this.add.tileSprite(0,0, this.world.width, this.world.height, 'background');
this.background.autoScroll(-SPEED,0);

Step 4. At this point we have enough to see the background scrolling by based on our SPEED constant. Refresh the browser to see the background scroll.

Step 5. Next, add the following constant, which will represent the gravity in our game:

var GRAVITY = 900;

Step 6. Add the following to the top of the create() function to setup the physics engine:

this.physics.startSystem(Phaser.Physics.ARCADE);
this.physics.arcade.gravity.y = GRAVITY;

Step 7. Now add the following to our create() method below our background texture:

this.player = this.add.sprite(0,0,'player');
this.player.animations.add('fly', [0,1,2], 10, true);
this.physics.arcade.enableBody(this.player);
this.player.body.collideWorldBounds = true;

Here we are creating a sprite instance from the sprite sheet image we previously loaded. Once we set the player sprite up we are going to create our fly animation. We do this by simply calling animations.add on the sprite itself and supply: a label for the animation, the frames, the amount of milliseconds between each frame and if it should loop.

Step 8. Refresh the browser and now you should see the players animate, and it should fall to the bottom of the screen due to gravity:

In most physics engines, a physics body represents the actual object collision area. It’s easy to define a downward pull by adding gravity to the y value of the player’s body object. Also, by setting the player.body.collideWorldBounds to true we tell the physics body that it should be constrained by the boundaries of the game’s world so the player doesn’t fall off the screen.

How To Start The Game

Now that we have a player and our background, let’s get started adding in a way to play our game. As we build this out, we’ll be taking advantage of the single state of our Phaser game so we’ll need to set up variables to represent the game modes to let us know when the it has started and when it is over. In order to do this we’ll need to create a function that will reset all of our games values first.

Step 1. Add the following function to our state object

update: function(){
},
reset:function(){
	this.gameStarted = false;
	this.gameOver = false;
	this.score = 0;
}

It’s important to note that you need to add a trailing comma to the previous function as you continue to add new functions to the game’s state object so we don’t get an error.

Step 2. Let’s add a call to reset()at the end of our create() function like so:

this.reset();

Now we have a convenient way to reset all of our game values at anytime by calling the reset() function. Not only will this help us get the game ready in the create() function but later on in the when we want to restart the game.

Step 3. Now we need to do a few things in order to build out our intro loop. Add the following to our reset() function:

this.player.body.allowGravity = false;
this.player.reset(this.world.width / 4, this.world.centerY);
this.player.animations.play('fly');

Here you can see that we are turning off our player’s gravity, resetting his position and setting the animation to fly.

Step 4. Now that our player in the correct position for the intro loop, let’s move the background.autoScroll() out of our create() function and put it into the reset() function with the following modification to the x value:

reset:function(){
    this.background.autoScroll(-SPEED * .80 ,0);

Here you’ll notice that we are now to multiplying the SPEED constant by .80 which will slow it down a bit and give us a nice little parallax effect when we add in the walls later on in the tutorial.

Step 5. At this point you can refresh the browser to see the player stays in one place and the background is scrolling a little slower:

Step 6. Now we will need to start building in the logic to differentiate between the attract loop and game play.  Let’s add the following to the update() function:

update: function(){
    if(this.gameStarted){

    }else{
        this.player.y = this.world.centerY + (8 * Math.cos(this.time.now/200));
    }
},	

Here we test if the gameStarted value is true, which means the game is running. If it is false we know that we are in the intro loop. During the intro loop we are going to automatically move the player sprite up and down like he is floating until the player starts the game. You can see that we use Math.cos to modify the y position of the player over each frame, which will give us our up and down motion.

Step 7. Refresh the game in the browser and can see the effect.

Displaying Text

At this point we have our intro loop but we don’t have a way to let the player know what they should do next. We’ll create some text that will not only tell the player how to start the game but also will be used to display the score when the game is running.

Step 1. Add the following code below where we setup our player sprite in the create() function:

this.player.body.collideWorldBounds = true;

this.scoreText = this.add.text(
    this.world.centerX,
    this.world.height/5,
    "",
    {
        size: "32px",
        fill: "#FFF",
        align: "center"
    }
);

As you can see, Phaser supports canvas text and also embedded web fonts if you have them loaded up into your page. To keep things simple we’ll just use the default font, which is Arial. Here we are setting the x and y position of the text, passing it an empty string to start with and defining an object for how the text should be styled.

Step 2. Now we’ll need to set some text to be displayed. To do this, we’ll set it up in the restart() function then add the following to it:

this.scoreText.setText("TOUCH TO\nSTART GAME");

You can use \n to create line breaks in your text.

Step 3. Refresh browser and you should now see the text rendering correctly:

While we can now see our start text, you’ll notice that it’s off center. We can use a built-in feature of Phaser that allows us to anchor elements.

Step 4. In our create() function, right after we instantiated our scoreText instance, add the following code:

        align: "center"
    }
);
this.scoreText.anchor.setTo(0.5, 0.5);

This will center the anchor position of the text object which helps give the impression that it is properly align when displayed.

Step 5. Refresh the browser to see the changes

Now that we have our intro loop complete, let’s look into how to start our game.

Starting The Game

In this section we are going to wire up our game to start when the player presses the mouse button and if the game is running, we’ll make our player fly up.

Step 1. We’ll need to create our start function on the state object:

start: function(){
    this.player.body.allowGravity = true;
    this.scoreText.setText("SCORE\n"+this.score);
    this.gameStarted = true;
}

Just like we did before, make sure you remember to insert a comma before you add this function. When called, this will enable the player’s gravity again. Next, we change the display to show the score and set the gameStarted flag to true.

Step 2. Now we need a way of calling the start() function. We’ll be adding a single function that will handle any mouse click. Let’s go ahead and create the jet() function on our state object:

jet: function(){
    if(!this.gameStarted){
        this.start();
    }

    if(!this.gameOver){
        this.player.body.velocity.y = -JET;
    }
}

Here we are testing if the game has not started when the function is called. If the game is in the intro loop mode, meaning that gameStarted is false, we call start() to begin the game. If the game is not over, we also change the velocity of the player’s body. By changing the velocity.y value we immediately send the player flying up. You’ll notice that we are applying a negative value to move up. Now we just need our JET constant.

Step 3. Add a constant for the JET value at the top of our game’s code:

var JET = 420;

Step 4. Now in our create() method, we can bind the mouse click to call our jet() function above where we call this.resent() like so:

this.input.onDown.add(this.jet, this);
this.reset();

Phaser handles the mouse input for us by allowing you to easily bind the onDown event to a function, in this case jet(), and supply a scope for the callback. This last bit is critical for maintaining scope in your game as you bind events. By passing this along with the reference to the jet() function we can safely reference properties in the game state like we have been in other places of our code.

Step 5. Now we are ready to refresh the browser and test out flying up and falling down.

Step 6. At this point we are ready to clean up the player animations. Add the following to the update() function, inside where we test if the game has started. We stop the jet animation when the player is falling and start it back up when the player is moving up:

update: function(){
    if(this.gameStarted){
        if(this.player.body.velocity.y > -20){
            this.player.frame = 3;
        }else{
            this.player.animations.play("fly");
        }

I usually tie all of my animations to the game object’s physics, in this case testing the value of the player’s velocity and updating the animation to reflect that movement. You’ll note that we set the fall frame number manually to display when the jet is off. It’s not critical to create a one-frame animation if you know the correct sprite ID.

Step 7. Refresh the browser to test out the new animations we added to the player:

How To End The Game

We now have everything we need in order to run our game, with the exception of detecting when the game is over.

Step 1. To create the game over logic we are going to need to figure out when the player actually hits the bottom of the screen and goes “out of bounds”. Add the following code just below where we setup our player’s animation in the update() function:

        this.player.animations.play("fly");
    }

    if(!this.gameOver){
        if(this.player.body.bottom >= this.world.bounds.bottom){
            this.setGameOver();
        }
    }
}else{
    this.player.y = (this.world.height/2) + 8 * Math.cos(this.time.now/ 200);

Here you can see we are testing to make sure that the game is not over. This will keep the setGameOver() function from getting called continuously when the player touches the bottom of the screen. Once we verify that the game is not over, we test to make sure the player’s body is above the bottom of the world bounds. Phaser has several shortcuts for getting values from game objects.  Accessing the .bottom property keeps us from having to manually configure the player’s dimensions.

 

Step 2. Now we need to create our setGameOver() function:

setGameOver: function(){
    this.gameOver = true;
    this.scoreText.setText("FINAL SCORE\n"+ this.score+"\n\nTOUCH TO\nTRY AGAIN");
	this.background.autoScroll(0, 0);
}

Here you’ll see that we set the gameOver flag to true, change the text to reflect that the game is over and stop the background from scrolling.

Step 3. At this point we have enough logic to actually test that our game can end. Refresh the browser and let the player fall to the bottom of the screen.

Now we need a way to restart out game.

Step 4. Let’s modify our jet() function where we test if the game is over. Add the following else condition to that logic block like so:

if(!this.gameOver){
    this.player.body.velocity.y = -JET;
}else if(this.time.now > this.timeOver + 400){
    this.reset();
}

You’ll notice that we are testing a new variable called timeOver. The basic idea here is that we are creating a simple delay between the time that the game is over, and when the player can click to restart. At the end of most game sessions, the player is frantically clicking away before they die to try and extend their session.  Without a delay before restart, the player would accidentally restart the game without seeing their final score. To overcome this, we’re going to test that 400 milliseconds have passed before we actually let the player restart the game, giving them just enough time to see their final score.

Step 5. To make this fully work we’ll want to save the timeOver value when the player dies. Add the following to our the end of our setGameOver() function:

this.timeOver = this.time.now;

By saving out the current game’s time.now value we are able to track how many milliseconds go by before we allow the player to reset the game.

Step 6. Refresh browser and give it a try. You should now be able to fully start, end and restart the game.

Conclusion

Our game is starting to come together. We have sprites on the screen, we are able to control the player to make them fly, we have an intro loop, the game, and a “game over” state to manage. Coming up next we will add in our obstacles, add collision detection, score, points and talk about publishing our game.

Phaser Part 3

- Jesse Freeman (@jessefreeman)

 

July 11, 2014

Jesse Freeman

In this tutorial we are going to create the “new hello world” in gaming, a Flappy Bird style game. We’ll be using Phaser, which is a popular HTML5 game framework, and the game we are going to build will feature the main character from my Super Jetroid game along with a few obstacles from my free Space Exploration Art Pack. In the first part of this three part series we are going to cover the following:

  • How To Configure Your Environment (CodePen, NodeJS and Apache)
  • Setting up Phaser

Before we dig into the code, you can check out the live demo of the game here.

How To Configure Your Environment

The next three sections will walk you through three different configuration options: CodePen.io, NodeJS + Grunt and Apache local server.

Simply pick the one you feel the most comfortable with, and once you have your environment configured you can move ahead to setting up Phaser itself. It’s important to note that each of these development options have advantages and disadvantages.  Which option you choose depends on your technical comfort level and your past experience building HTML5 content.

Option #1:  CodePen.io: Online Editor

Sometimes the hardest part of making an HTML5 game is setting up the development environment. To help make this as easy as possible, you can actually use an online code editor such as CodePen.io in order to run all of the code we’ll cover in this Introduction to Phaser tutorial. The advantage here is that you don’t have install anything on your computer. The disadvantage is that you will not be able to really publish and share your game; you’ll still end up having to host it online somewhere else.  This means, you’ll need to rewrite the code to be standalone which I will not cover in this tutorial. Here are instructions for setting that up.

Step 1. You will need to create a new account on CodePen.io.

Step 2. Create a new project.

Step 3. Add the following to the HTML Window

<div id=“game”></div>

This will give us an empty div where we can put our game.

Step 4. Now we’ll need to add the following into the CSS Window

body {

    background: #333;

    margin: 0;

    padding: 0;

}

#game {

    margin: 0 auto;

    max-height: 568px;

    max-width: 320px;

}

This will represent our default CSS for the body of the page and the game div itself.

Step 5. We need to configure an external JS file for the project. We’ll be using a version of Phaser I have hosted on my server. Click on the gear icon to the left of the JS window and paste the following url in the “External JS File” field:

http://games.jessefreeman.com/wp-content/public/workshop/phaser/phaser.min.js

You should have something that looks like this:

Step 6. At this point we are done with the basic configuration, so make sure to minimize the HTML and CSS windows so you have a larger place to work on your code.

One thing to note when using CodePen is that you’ll need to load all of the artwork and sounds from an online server. We’ll cover this later in the tutorial but just keep in mind that you will need to preface the url path to all of the assets we load as part of this tutorial with the following url (which is coming from my personal website):

http://games.jessefreeman.com/wp-content/public/workshop/phaser/

As an aside, you may have issues loading your own artwork into a CodePen project if you are not a pro member and using their hosting solution. To get around this, I have a .htaccess file in the root of my server’s public folder with the following:

<IfModule mod_headers.c>

    Header set Access-Control-Allow-Origin "*"

</IfModule>

This allows you to bypass the cross-domain issues you normally get when loading images from severs on a different domain.

At this point we are ready to move on so you can skip the next two sections on setting up the project locally with NodeJS and Grunt or Apache.

Option #2:  NodeJS + Grunt: Local Automated Build Process

I am a big fan of having an automated build process when I develop HTML5 games. For all of my projects I use NodeJS and Grunt. This automated build process will compile the game’s code into a single JS file for you any time you make a code change and hit save. The workflow also sets up a temporary server to run your game locally and even opens your browser to the correct URL making the entire setup and development process dead simple once it’s fully configured.

To help you get started I have created a Phaser Template Project which you will need to download in addition to NodeJS, Grunt and the project’s dependent modules. The following steps will walk you through this process from scratch. If you already have node and grunt installed, simply skip ahead to step 2.

Step 1. You will need a copy of NodeJS, which works on Mac, PC and Linux. Simply go to http://nodejs.org and get the correct installer for your computer. Once it’s installed you want to open up the command line and type in the following:

> npm

You should see something like the following:

This means that NPM (Node Package Manager) is installed and you can continue on with the rest of the setup process.

Step 2. Next we’ll need to install Grunt on the command line. If you have never used Grunt before, you can learn more about it at http://gruntjs.com. For now, enter the following in the command line:

> npm install -g grunt-cli

Step 3. At this point you have everything you need to support the automated workflow. Next you’ll want to download my Phaser Project Template from https://github.com/gamecook/phaser-project-template and unzip it on your computer where you do your development.

Step 4. Let’s go ahead and rename the Phaser Template Project to phaser-demo.

Step 5. Now we need to install the project’s module dependencies that will allow us to run the Grunt build script. Open up the command line and navigate to the project folder. Once inside, type the following command.

> npm install

You’ll see the following in the terminal window:

 

If you get an error for any reason, simply re-run the command again.

Step 6. Run the following command to start the grunt task:

> grunt

Once the command is executed your browser should automatically open showing you the default project page and display the current Phaser build version.

Phaser is a very active project, so your build number may be slightly higher then what is displayed above. As of this writing, the current version of Phaser is v2.0.3. As long as you have the Grunt task running, your project will automatically recompile every time you make a change to any JavaScript file inside the src directory. Once the project is recompiled, simply refresh your browser to see the changes. Also, make sure you disable your browser's cache.

This template project has everything you need to build your own Phaser game. You’ll find the game’s source file in the src/game folder called main.js.

 

 

Phaser’s source code is inside of the lib folder. You can update Phaser on your own at any point by simply replacing the phaser.min.js file in that folder. Just be careful because newer versions of Phaser may break your game’s code.

Since this project is pre-configured to display the Phaser version number, you will want to open up the main.js file and delete all the code inside of it so that it’s blank before you get started building your new game. Now you can skip ahead to the Setting up Phaser section of the tutorial.

Option #3:  Apache as a Local Server

Phaser is just like any other HTML/JS project you have ever worked with. If CodePen and NodeJS/Grunt are not your thing, simply run the game from Apache or any web server you are familiar with. Let’s look at how to setup the Phaser Project Template from the NodeJS configuration setup inside of Apache.

Step 1. Make sure you have Apache installed. I suggest using one of the following depending on your OS:

Step 2. Once Apache is installed and running, you will need to download my Phaser Project Template (https://github.com/gamecook/phaser-project-template) and put it in your Apache’s web root.

Step 3. Now you will want to move main.js and phaser.min.js from src folder into deploy/js folder. Since we are not automatically compiling these two files, we’ll just manually set them up like any regular script tag reference in an HTML file.

Step 4. Open up the index.html file inside of the deploy folder and fix the paths. You will need to load both js files like so:

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

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

Step 5. At this point you are ready to load the project up in the browser. Navigate to your Apache’s localhost and go into the deploy folder. You should see the following:

Note that your url may be different depending on what port your Apache is configured to use. You may also see a different Phaser version number than what is displayed above. As of this writing, Phaser 2.0.3 is the latest build.

Step 6. Now that everything is working, open up the main.js file that should now be located in your deploy/js directory and delete everything inside of it. Then you’ll be ready to start the tutorial in the next section.

Setting Up Phaser

The hard part of configuring our environment is now behind us and it’s time to build our first Phaser game.

Step 1. At this point you should have an empty main.js file if you are using the Phaser Project Template or an empty JS window in CodePen.

Step 2. Type out the following object, which we will assign to a state variable:

var state = {
    preload: function(){
    },
    create: function(){
    },
    update: function(){
    }
}

Phaser uses a notion of “states” to represent each screen of your game. Think of the state as a place to keep all of the logic that belongs in that scene. Phaser will take a state and wire it up to the main game engine to run your code. When creating states, we’ll take advantage of a few functions such as preload(), create() (which is run first when a state is created and done preloading), and update() (which is run before the draw call). While Phaser has other state functions available, we’ll only be focusing on these three main ones for this tutorial.

Step 3. Now it’s time for us to create an instance of the actual Phaser game. Add the following code below where we created our state object:

var game = new Phaser.Game(
    320,
    568,
    Phaser.AUTO,
    'game',
    state
)

This will represent our Phaser game. Here you can see we are creating an instance of Phaser.Game as well as supplying the width and height. We are going to set the render mode of Phaser to Phaser.AUTO. This will detect what rendering options your browser supports and either run the game with WebGL support or call back to software based 2d Canvas. Finally we define the name of the div where our game should be created as well as pass in a reference of the initial state object.

Step 4. Now you are ready to refresh browser. You should see that we simply have a black box representing where our game will eventually go.

Conclusion

At this point you should now have a stable work environment for building Phaser games as well as the initial game code setup to build upon in the next parts of this tutorial. Coming up next, well talk about preloading, displaying images and building out some basic game mode logic for starting, playing and ending our game.

Phaser Part 2

- Jesse Freeman (@jessefreeman)

 

Want the latest?

appstore topics

Recent Posts

Archive