14

Starship Defender: An HTML5 Game Tutorial using the Phaser

  • Upload
    others

  • View
    7

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Starship Defender: An HTML5 Game Tutorial using the Phaser
Page 2: Starship Defender: An HTML5 Game Tutorial using the Phaser

Starship Defender: An HTML5 Game Tutorialusing the Phaser Framework

James Allan

This book is for sale at http://leanpub.com/starshipdefender

This version was published on 2016-07-26

This is a Leanpub book. Leanpub empowers authors and publishers with the Lean Publishingprocess. Lean Publishing is the act of publishing an in-progress ebook using lightweight tools andmany iterations to get reader feedback, pivot until you have the right book and build traction onceyou do.

© 2016 James Allan

Page 3: Starship Defender: An HTML5 Game Tutorial using the Phaser

To my loving Catherine

Page 4: Starship Defender: An HTML5 Game Tutorial using the Phaser

Contents

Adding Sprites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1Loading An Image . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1Creating a Game Sprite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2Moving Sprites and the Game Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3Sprite Origins or Anchor Points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5Commenting and Commenting Out Code . . . . . . . . . . . . . . . . . . . . . . . . . . 8The Code so far . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9What You Have Learned . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

Page 5: Starship Defender: An HTML5 Game Tutorial using the Phaser

Adding SpritesLoading An Image

A blank game screen isn’t all that interesting but it is a blank canvas on which we can begin buildingour game. So let’s start by loading and placing a game sprite in our game and playing around a littlebit.

With Brackets open, click on the “Game.js” file in the left hand directory, scroll down to the preloadmethod starting around line 31 and type in the following code:

preload: function () {

// Preload the game images, sounds, etc first before starting the game

this.load.image();

},

Notice that the end of the line of code has a semi-colon(;). This tells Phaser to terminate orend this piece of code. As you go through the code examples, be sure that you don’t forgetto terminate your lines of code as it can be a source of program errors.

The preload method is a built-in method provided by the Phaser framework that makes sure thatall the graphics and sounds are downloaded and ready for use before any other code is run.

The load method for images is expecting two parameters inside the brackets or parenthesis:* A name or key to reference the image in the Phaser game cache (a bit like the browser cache)* where can we find this image in the project “assets” folder.

Let’s load “player_solo.png” to get us started.

preload: function(){

// Preload the game images, sounds, etc first before starting the game

this.load.image('player', 'assets/sprites/player_solo.png');

},

1

Page 6: Starship Defender: An HTML5 Game Tutorial using the Phaser

Adding Sprites 2

Player Sprite

We’ve given our image the name (or ‘key’) of ‘player’ which we’ll use when we create the sprite.Also note that we use a comma (,) to separating the two pieces of information or data.

if you run the game now, nothing will have changed on the game screen because we haven’t actuallymade a sprite yet, just loaded the image it will use. To create a sprite, we use the create methodwhich you’ll find just below the preload method.

If you test the game and get a blank or black screen there is an error. It is likely just atypo or mistake in entering the line of code above. Double check you’ve spelt everythingcorrectly and have the correct punctuation.

Creating a Game Sprite

First we’ll create an object variable called player and assign the Phaser sprite properties andmethodsto it.

create: function(){

this.player = this.add.sprite(400, 300, 'player');

},

The player variable can have whatever name we want (it’s our variable), we just have tomake sure it’s unique and easy to remember.

When creating a new sprite, 3 pieces of data are expected: * Where to place the sprite on the screen(the x and y coordinates) * The image to be use for the sprite .

The screen coordinates start at 0, 0 (x, y) and always starts at the top left corner of the screen. Thegame world dimensions are infinite and extend beyond the 800 pixel width and 600 pixel height ofthe game screen we see in all directions.

Page 7: Starship Defender: An HTML5 Game Tutorial using the Phaser

Adding Sprites 3

Screen Coordinate System

When we placed the Player sprite at (400, 300) that is halfway across the screen and halfway downor somewhere in the middle of the screen. Save the “Game.js” file and take a look at the game now.

Player sprite placed in-game

The player sprite is at approximately the center of the screen. Try some different numbers to placethe sprite in different parts of the screen. If you enter numbers that are greater than the screendimensions of 800 x 600 or negative numbers, the sprite may not be visible as it will be placedsomewhere outside the visible area of the game world.

Moving Sprites and the Game Loop

To make our Player sprite move, we need to increase or decrease (increment or decrement) itscoordinates or its x and y position. That means adding a number not just once but many times

Page 8: Starship Defender: An HTML5 Game Tutorial using the Phaser

Adding Sprites 4

over a period of time. We can do that in the update method found just below the create method.

Add the following code to the update method:

update: function () {

// This is the game loop.

this.player.x = this.player.x+1;

}

The update method is the “game loop” and the code inside the update method is run or executedevery frame the game is running. All we’re doing here is making the player’s current X positionequal the player’s current X position plus 1, every time we pass through the update method.

Save and test your game in the browser and you should see the player moving slowly across thescreen.

There is a simpler way of writing this which does exactly the same thing:

this.player.x += 1;

We can also make the player move in the opposite direction by changing the + (plus) to a - (minus).

this.player.x -= 1;

Play with the numbers for a little while. Try larger numbers or smaller numbers like 0.2 or 1.3.

Add a new line of code that updates the y position.

When you see the sprite leave the screen, it hasn’t gone, it’s still travelling off forever in the directionyou sent it in, you just can’t see it anymore.

Let’s try something else, let’s rotate the player’s sprite. Change the .x to .angle in the code so itlooks like this:

update: function () {

// This is the game loop.

this.player.angle += 1;

}

Now that looks kind of odd doesn’t it. The player sprite is not rotating around its center. Let’s fixthat.

Page 9: Starship Defender: An HTML5 Game Tutorial using the Phaser

Adding Sprites 5

Sprite Origins or Anchor Points

The sprite’s origin or “anchor point” by default is in the upper left corner of the sprite image (0, 0)just like our game screen coordinates start in the upper left corner.

Sprite default anchor point

Ideally, we want the anchor point to be at the center of our sprite. Fortunately, Phaser has a methodfor changing the anchor point so that we can customize our sprite.

First to see where the anchor point is, let’s place a marker dot on the current location of the anchorpoint of our player sprite.

In the render method, add the following code:

render: function(){

var anchor = new Phaser.Point(this.player.x, this.player.y);

this.game.debug.geom(anchor, 'rgba(255, 255, 255, 1)');

}

Watch that you don’t miss any punctuation or misspell a word. Computers are not smartenough to figure out spelling mistakes or grammar :)

The Phaser.Point will be placed at the player’s (x, y) coordinates.

When you run the game you should see a small white box in the upper left corner of the playersprite. Now we can see clearly that the player is rotating around the anchor point in the upper lefthand corner.

Page 10: Starship Defender: An HTML5 Game Tutorial using the Phaser

Adding Sprites 6

Anchor rotation point

Go back to the create method, enter a new line after the player sprite and add this code to changethe location of the anchor point on the sprite.

create: function(){

this.player = this.add.sprite(400, 300, 'player');

this.player.anchor.setTo(0.5, 0.5);

},

Test the file now and the sprite will be rotating around it’s center.

We could have changed the x and y anchor point locations separately like sothis.player.anchor.y = 0.5 but using setTo is more efficient. We could take this a stepfurther and simply type this.player.anchor.setTo(0.5) and Phaser would know thatboth x and y should equal 0.5.

Page 11: Starship Defender: An HTML5 Game Tutorial using the Phaser

Adding Sprites 7

Centred anchor point

What we’ve done here is to change the sprite’s anchor property using the setTomethod and movedit along 50% of the width and 50% of the height of the sprite’s (x, y).

We represent 50% using 0.5 and we get that by taking 50% and dividing it by 100% or 50% = 50/100= 0.5

If we wanted to move the anchor point to the bottom and middle of the sprite, then we would writeit as (0.5, 1).

The y value = 1 which represents 100% divided by 100% or 100% = 100/100 = 1.

You can also go higher than 1 or even negative, this will place the anchor point away from the spritecreating an “offset”. This can be useful.

Try 3 on the x-axis to move the anchor point 300% along the width.

this.player.anchor.setTo(3.0, 0.5);

Cool huh? It’s like the ship is circling or orbiting the white marker.

Play with the numbers for a while until you feel comfortable with how it affects the sprite.

When you’re done, put the anchor values back to (0.5, 0.5).

Like the update method, the render method is run every frame of the game.

Page 12: Starship Defender: An HTML5 Game Tutorial using the Phaser

Adding Sprites 8

Commenting and Commenting Out Code

Youmay have already noticed that there are what are called “comments” in the code we have. Theseare lines that appear greyed out and start with two forward slashes like so: //

When the game program runs and it sees these two forward slashes, program ignores everythingafter them. That is why they are usually greyed out in your editor.

We can use the same thing for lines of code we want the game or program to ignore. This is veryuseful when we want to temporarily try something out or are tracking down a bug in our code(debugging).

Before we continue, comment out the player angle code in the update method and the two lines ofcode in the render method. We no longer need these but we may come back to them later, so keepthem handy.

update: function () {

// This is the game loop.

//this.player.angle += 1;

},

// After the update method, we can make our own methods here.

render: function(){

//var pivot = new Phaser.Point(this.player.x, this.player.y);

//this.game.debug.geom(pivot, 'rgba(255, 255, 255, 1)');

}

Page 13: Starship Defender: An HTML5 Game Tutorial using the Phaser

Adding Sprites 9

The Code so far

preload: function () {

// Preload the game images, sounds, etc first before starting the game

this.load.image('player', 'assets/sprites/player_solo.png');

},

create: function () {

// We instantiate or make our game objects here

this.player = this.add.sprite(400, 300, 'player');

this.player.anchor.setTo(0.5, 0.5);

},

update: function () {

// This is the game loop.

//this.player.angle += 1;

},

// After the update method, we can make our own methods here.

render: function(){

//var pivot = new Phaser.Point(this.player.x, this.player.y);

//this.game.debug.geom(pivot, 'rgba(255, 255, 255, 1)');

}

Page 14: Starship Defender: An HTML5 Game Tutorial using the Phaser

Adding Sprites 10

What You Have Learned

• How to preload an image• How to create a game sprite• How to move a sprite using the update method and simple math• How to change the anchor point of a sprite or game element using anchor.setTo();• How to use the render method to see the anchor point (for debugging)• How to rotate a sprite using the angle property in the update function