Example 16. TileSprite

We use the same image as in the previous example. This time we use it as only 1 image.


We tile this image, using tileSprite method.


This is the javascript file which adds 5 by 5 tiles, anchored around center of screen and starts autoscrolling.



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// ex16. TileSprite

var GameState = {

    preload: function() {

        game.load.image('colorImages', 'images/ex16.png');
    },

    create: function() {

        // Set backgound color
        game.stage.backgroundColor = "#555555";

        // Image size
        var imageWidth = 64, imageHeight = 64;

        // parameters for tile placement
        var numTiles = 5;
        var x = game.world.centerX - numTiles / 2 * imageWidth;
        var y = game.world.centerY - numTiles / 2 * imageHeight;
        var w = numTiles * imageWidth;
        var h = numTiles * imageHeight;

        // tileSprite added and scrolling started
        this.color = game.add.tileSprite(x, y, w, h, 'colorImages');
        this.color.autoScroll(imageWidth / 2, imageHeight / 2);
    }
}

var game = new Phaser.Game(800, 600, Phaser.AUTO);
game.state.add("GameState", GameState);
game.state.start("GameState");

This is the output during the scrolling:




Example 15. Animation

We will use this image with four rectangles:




The image is 64 by 64, and spritesheet is loaded with key 'colorImages' and each frame is 32 by 32 bits. We also indicate there are four of them.


This is the javascript file which creates an animation 'colorAnimation' that go from frame 0 to 3 and then repeats at a rate of 2 frames per second:



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// ex15. Animation

var GameState = {

    preload: function() {

        game.load.spritesheet('colorImages', 'images/ex15.png', 32, 32, 4);
    },

    create: function() {

        // Set backgound color
        game.stage.backgroundColor = "#555555";

        // add first frame
        this.color = game.add.sprite(game.world.centerX,
                                     game.world.centerY, 'colorImages');
        this.color.anchor.setTo(0.5);
        this.color.scale.set(4);

        // create looped animation
        this.color.animations.add('colorAnimation', [0, 1, 2, 3], 2, true);

        // start
        this.color.animations.play("colorAnimation");
    }
}

var game = new Phaser.Game(800, 600, Phaser.AUTO);
game.state.add("GameState", GameState);
game.state.start("GameState");

During the animation, we will have one of the four colors and it will change at a rate of 2 per second.




Example 14. moveToXY

If a sprite has physics enabled, we can use moveToXY method to move it to some direction. We use mouse coordinates, from the last click to move the sprite to.


moveToXY returns angle of rotation which we can set the sprite rotation attribute to. This assumes the arrow initial state is rightwards where rotation angle is zero.


This is the javascript file which calls moveToXY in the callback to the click.



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// ex14. moveToXY

var GameState = {

    preload: function() {

        game.load.spritesheet("arrow", "images/arrow.png");
    },

    create: function() {

        // Set backgound color
        game.stage.backgroundColor = "#0FFF0F";

        // Start Physics
        game.physics.startSystem(Phaser.Physics.ARCADE);

        // Player centered and physics, initial left velocity
        this.player = game.add.sprite(game.world.centerX, game.world.centerY, "arrow");
        this.player.anchor.setTo(0.5);
        game.physics.enable(this.player, Phaser.Physics.ARCADE);
        this.player.body.collideWorldBounds = true;

        // move toward upperleft, and face towards it
        rot = game.physics.arcade.moveToXY(this.player, 0, 0, 100);
        this.player.rotation = rot;

        // listen to mouse click
        game.input.onDown.add(this.move, this);
    },

    move: function() {
        // move to click point, face towards it
        var x = game.input.activePointer.x;
        var y = game.input.activePointer.y;
        var rot = game.physics.arcade.moveToXY(this.player, x, y, 100);
        this.player.rotation = rot;
    }
        
};

var game = new Phaser.Game(800, 600, Phaser.AUTO);
game.state.add("GameState", GameState);
game.state.start("GameState");

This is the output:


Example 13. Arrow Keys

Using createCursorKeys() method in our create() method, we can check the directions left, right, up and down arrows with isDown() in our update() method.


This program moves a sprite left, right, up or down by setting its velocity in one of the directions. Once a key is pressed and released, it will continue in that direction until new arrow key is pressed. However it will not be able to leave the world. Also it keeps changing sprite angle so it keeps facing direction it is moving.



This javascript file sets the physics and changes velocity in response to arrow keys.



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// ex13. Arrow Keys

var GameState = {

    preload: function() {

        game.load.spritesheet("arrow", "images/arrow.png");
    },

    create: function() {

        // Set backgound color
        game.stage.backgroundColor = "#0FFF0F";

        // Start Physics
        game.physics.startSystem(Phaser.Physics.ARCADE);

        // Player centered and physics, initial left velocity
        this.player = game.add.sprite(game.world.centerX, game.world.centerY, "arrow");
        this.player.fame = 2;
        this.player.anchor.setTo(0.5);
        game.physics.enable(this.player, Phaser.Physics.ARCADE);
        this.player.body.collideWorldBounds = true;
        this.player.body.velocity.setTo(-100,0);

        // listen to the arrow keys
        this.cursor = game.input.keyboard.createCursorKeys();
    },

    update: function() {

        // was arrow key pressed
        if(this.cursor.left.isDown) {
            this.player.body.velocity.setTo(-100, 0);
            this.player.angle = 0;
        } else if (this.cursor.right.isDown) {
            this.player.body.velocity.setTo(100, 0);
            this.player.angle = 180;
        } else if (this.cursor.up.isDown) {
            this.player.body.velocity.setTo(0, -100);
            this.player.angle = 90;
        } else if (this.cursor.down.isDown) {
            this.player.body.velocity.setTo(0, 100);
            this.player.angle = 270;
        }
    }
};

var game = new Phaser.Game(800, 600, Phaser.AUTO);
game.state.add("GameState", GameState);
game.state.start("GameState");


This is the output:

Example 12. Reading JSON

A JSON file is written with a value for x and a value for y:



1
2
3
4
{
  "x": 300,
  "y": 200
}


This javascript file reads the JSON file and set the sprite coordinates.



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// ex12. Reading JSON

var GameState = {

    preload: function() {

        game.load.image("red", "images/red.png");
        game.load.text("coord", "data/coord.json");
    },

    create: function() {

        // Set backgound color
        game.stage.backgroundColor = "#0FFF0F";

        // Coordinates
        var data = JSON.parse(game.cache.getText("coord"));
        var x = data.x;
        var y = data.y;

        //  sprite at x, y location
        this.red = game.add.sprite(x, y, "red");

    }
};

var game = new Phaser.Game(800, 600, Phaser.AUTO);
game.state.add('GameState', GameState);
game.state.start('GameState');


This is the output:


Example 11. Physics

We can use Physics to create the same animation as in Example 10.


We have to set the physics on game and the sprite. Also we make sure the sprite is bound to the game dimensions.


We use the moveTo method of the physics engine to move sprite to lower right corner. Had we not set the bounds, it would continue moving and out of the screen.


This is the javascript file. The output is similar to the previous Example.



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// ex11. Physics

var game = new Phaser.Game(800, 600, Phaser.AUTO);

var GameState = {

    preload: function() {

        game.load.image("red","images/red.png");
    },

    create: function() {

        // Set backgound color
        game.stage.backgroundColor = "#0FFF0F";

        // Start sprite at upper left Corner
        this.red = game.add.sprite(0, 0, "red");

        // Stopping Point is lower right corner
        var x = game.width - this.red.width;
        var y = game.height - this.red.height;
        
        // start physics
        game.physics.startSystem(Phaser.Physics.ARCADE);

        // sprite physics on red
        game.physics.enable(this.red, Phaser.Physics.ARCADE);
        this.red.body.collideWorldBounds = true;

        // move diagonally
        game.physics.arcade.moveToXY(this.red, x, y, 100);
    }
};

game.state.add('GameState', GameState);
game.state.start('GameState');

Example 10. Animation

An animation can use the tween method to go from current state to another state, over a certain duration.


Here a sprite moves diagonally from upper left corner to lower right corner of the screen.


This is the javascript file:



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// ex10. Animation

var game = new Phaser.Game(800, 600, Phaser.AUTO);

var GameState = {

    preload: function() {

        game.load.image("red","images/red.png");
    },

    create: function() {

        // Set backgound color
        game.stage.backgroundColor = "#0FFF0F";
        
        // sprite at Upper Left Corner
        this.red = game.add.sprite(0, 0, "red");

        // diagonal movement over 10 sec
        var redMovement = game.add.tween(this.red);
        var moveTo = {
            x : game.width - this.red.width,
            y : game.height - this.red.height
        };
        redMovement.to(moveTo, 10000);
        redMovement.start();
    }
};

game.state.add('GameState', GameState);
game.state.start('GameState');


This is the output near the halfway point:


Example 9. Update

The update function is called at each frame.


Similar to previous example, we increase the angle of the sprite. However now, instead of clicking, it will automatically increase.


We increase the angle by 1 each time.


This the javascript file:



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// ex09. Update

var game = new Phaser.Game(800, 600, Phaser.AUTO);

var GameState = {

    preload: function() {

        game.load.image("red","images/red.png");
    },

    create: function() {

        // Set backgound color
        game.stage.backgroundColor = "#0FFF0F";
        
        // center coordinates
        var x = game.world.centerX;
        var y = game.world.centerY;

        // Red sprite, rotates around center (anchor point)
        this.red = game.add.sprite(x, y, "red");
        this.red.anchor.setTo(0.5);
    },

    update: function() {
        this.red.angle++;
    }
}

game.state.add('GameState', GameState);
game.state.start('GameState');


The output should be similar to last example.

Example 8. Rotate

We can set the angle of a sprite, at different times, so it will rotate.


We use a red image, centered on screen, and rotated by 15 degrees each time a click is detected.


Initially this.red.angle will be zero, and increase by 15 each time.


This is the javascript file:



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// ex08. Rotate

var game = new Phaser.Game(800, 600, Phaser.AUTO);

var GameState = {

    preload: function() {

        game.load.image("red","images/red.png");
    },

    create: function() {

        // Set backgound color
        game.stage.backgroundColor = "#0FFF0F";
        
        // center coordinates
        var x = game.world.centerX;
        var y = game.world.centerY;

        // Red sprite, rotates around center (anchor point)
        this.red = game.add.sprite(x, y, "red");
        this.red.anchor.setTo(0.5);

        // Listener for click
        game.input.onDown.add(this.rotate, this);
    },

    rotate: function() {
        this.red.angle += 15;
    }
}

game.state.add('GameState', GameState);
game.state.start('GameState');


This is the output after a few clicks:



Example 7. State

From now on, this is the HTML file that will be used:



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Phaser Example</title>
  <script type="text/javascript" src="js/phaser.min.js"></script>
</head>
<body>
  <script type="text/javascript" src="js/main.js"></script>
</body>
</html>


This is the javascript file. We are using the GameState object as our only game state.



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// ex07. State

var game = new Phaser.Game(800, 600, Phaser.AUTO);

var GameState = {
    create: function() {
        // Set backgound color
        game.stage.backgroundColor = "#0FFF0F";

        // Style for text
        var style = {
            font: 'bold 50pt Tarzan',
            fill: '#D0171B',
            align: 'center'
        }
        
        // center coordinates
        var x = game.world.centerX;
        var y = game.world.centerY;

        // Show text with x,y the center point
        this.text = game.add.text(x, y, 'Hello\nPhaser\nWorld', style);
        this.text.anchor.setTo(0.5);
    }
}

game.state.add('GameState', GameState);
game.state.start('GameState');

The only global variable is game. The variables we use in multiple functions should have this. before their name so their scope is the entire object, and thus in all functions belonging to it. Only local variables, local to a function, will be defined using var.


Thus we can this.text in other functions in this object if we wanted.


This generates the same output as in the previous example.

Example 6. Text

A text is added to the screen around the center point.


It is styled using Tarzan font.


This is the javascript file:



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// ex06. Text

var game = new Phaser.Game(800, 600, Phaser.AUTO, 'ex06',
               {create: create});

function create() {
    // Set backgound color
    game.stage.backgroundColor = "#0FFF0F";

    // Style for text
    var style = {
        font: 'bold 50pt Tarzan',
        fill: '#D0171B',
        align: 'center'
    }
    
    // center coordinates
    var x = game.world.centerX;
    var y = game.world.centerY;

    // Show text with x,y the center point
    text = game.add.text(x, y, 'Hello\nPhaser\nWorld', style);
    text.anchor.setTo(0.5);
}



This is the output:




Example 5. Audio

We can play a sound using the play method. Whenever we click on the greenish screen, a sound should be head.


This is the javascript file. We use this.sound as the variable name so its scope is this file.



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// ex05. Audio

var game = new Phaser.Game(800, 600, Phaser.AUTO, 'ex05',
               { preload: preload, create: create});

function preload() {
    game.load.audio('ex05Sound', 'sounds/ex05.mp3');
}

function create() {
    // Set backgound color
    game.stage.backgroundColor = "#0FFF0F";

    // sound
    this.sound = game.add.audio("ex05Sound");
    
    // call playSound if click detected
    game.input.onDown.add(playSound, this);
}

function playSound() {
    // Play sound
    this.sound.play()
}

Example 4. Group

We can use a group to add many images.


This is the javascript file:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// ex04. Group

var game = new Phaser.Game(800, 600, Phaser.AUTO, 'ex04',
               { preload: preload, create: create});
var blocks;

var index = 0;

function preload() {
    game.load.image('red', 'images/red.png');
    game.load.image('turquoise', 'images/turquoise.png');
    game.load.image('rose', 'images/rose.png');
    game.load.image('green', 'images/green.png');
}

function create() {
    // Set backgound color
    game.stage.backgroundColor = "#0FFF0F";

    // four overlapping images
    red = game.add.image(0, 0, 'red');
    turquoise = game.add.image(0, 0, 'turquoise');
    rose = game.add.image(0, 0, 'rose');
    green = game.add.image(0, 0, 'green');

    // create group with images
    blocks = game.add.group();
    blocks.add(red);
    blocks.add(turquoise);
    blocks.add(rose);
    blocks.add(green);

    // Center of screen
    var x = game.world.centerX;
    var y = game.world.centerY;
    blocks.x = x - blocks.width/2;
    blocks.y = y - blocks.height/2;

    // show red (image at index 0)
    changeColor();

    // call changeColor if click detected
    game.input.onDown.add(changeColor, this);
}

function changeColor() {
    // kill all 4 sub images
    blocks.callAll('kill')
    
    // revive only index
    blocks.getChildAt(index).revive()
    
    // new index value
    index = (index + 1) % 4;
}


The images are rectangles with the indicated color. Whenever, the game screen is clicked, we kill all 4 components and revive only that pointed by the index variable.


The output is identical to Example 1 except we do not have a separate div to indicate index value.

Example 3. Sprite

From now, we will have the standard html file below. The only difference would be the div id name and script name.



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Ex03</title>
  <script type="text/javascript" src="js/phaser.min.js"></script>
</head>
<body>
  <div align="center" id="ex03"></div>
  <script type="text/javascript" src="js/ex03.js"></script>
</body>
</html>

This is the javascript file:




 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// Ex03. Sprite

var game = new Phaser.Game(800, 600, Phaser.AUTO, 'ex03',
               { preload: preload, create: create});
var ball;

function preload() {
    game.load.image('ball', 'images/ex03.png');
}

function create() {
    game.stage.backgroundColor = "#0FFF0F";
    var x = game.world.centerX;
    var y = game.world.centerY;
    ball = game.add.sprite(x, y, 'ball');
    ball.scale.setTo(2,2);
    ball.anchor.setTo(0.5, 0.5);
    game.input.onDown.add(changePosition, this);
}

function changePosition() {
    ball.x = game.input.activePointer.x;
    ball.y = game.input.activePointer.y;
}

A ball image is used:




Now by clicking anywhere on the screen, the ball moves there:



Example 2. Random

Instead of changing frames in order (as in Example 1), in response to click, now there are randomly changed. They will be changed to a random value, which does not happen to be the current value.


This is the html file:



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Ex02</title>
  <link rel="stylesheet" type="text/css" href="css/ex02.css">
  <script type="text/javascript" src="js/phaser.min.js"></script>
</head>
<body>
  <div align="center" id="ex02"></div>
  <div align="center" id="frame"></div>
  <script type="text/javascript" src="js/ex02.js"></script>
</body>
</html>

The css file is identical to that in example 1.


This is the javascript file:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// Ex02. Random

var game = new Phaser.Game(800, 600, Phaser.AUTO, 'ex02',
               { preload: preload, create: create});
var colorBox;

function preload() {
    game.load.spritesheet('fourColors', 'images/ex02.png', 16, 16, 4);
}

function create() {
    game.stage.backgroundColor = "#00FFFF";
    colorBox = game.add.sprite(game.world.centerX, game.world.centerY, 'fourColors');
    colorBox.scale.setTo(10,10);
    colorBox.anchor.setTo(0.5, 0.5);
    colorBox.inputEnabled = true;
    colorBox.events.onInputDown.add(changeColor, this);
    displayFrame(colorBox.frame);
}

function changeColor() {
    var oldFrame = colorBox.frame;
    var newFrame = game.rnd.integerInRange(0, 3);
    while (newFrame == oldFrame) {
        newFrame = game.rnd.integerInRange(0, 3);
    }
    colorBox.frame = newFrame;
    displayFrame(colorBox.frame)
}

function displayFrame(frame) {
    document.getElementById("frame").innerHTML = "frame = " + frame;
}

Now we use rnd.integerInRange(0,3) function to get a random value from 0 to 3.


The while loop will ensure that we do not select same value.

Example 1. Spritesheet

A spritesheet can have multiple frames. This is an example sprite sheet with 4 frames:

The 32 by 32 image contains four 16 by 16 images of red, turqoise, rose and green blocks.



This is the main HTML file, ex01.html, using the Phaser gaming library:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Ex01</title>
  <script type="text/javascript" src="js/phaser.min.js"></script>
  <link rel="stylesheet" type="text/css" href="css/ex01.css">
</head>
<body>
  <div align="center" id="ex01"></div>
  <div align="center" id="frame"></div>
  <script type="text/javascript" src="js/ex01.js"></script>
</body>
</html>


This is the csv file, ex01.css:

1
2
3
4
5
6
7
8
9
#frame {
 width: 800px;
 margin: auto;
 font-family: "Arial";
 font-size: 96px;
 color: white;
 background: blue;
 text-align: center;
}


Finally the ex01.js JavaScript file is

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
var game = new Phaser.Game(800, 600, Phaser.AUTO, 'ex01',
               { preload: preload, create: create});
var colorBox;

function preload() {
    game.load.spritesheet('fourColors', 'images/ex01.png', 16, 16, 4);
}

function create() {
    game.stage.backgroundColor = "#00FFFF";
    colorBox = game.add.sprite(game.world.centerX, game.world.centerY, 'fourColors');
    colorBox.scale.setTo(10,10);
    colorBox.anchor.setTo(0.5, 0.5);
    colorBox.inputEnabled = true;
    colorBox.events.onInputDown.add(changeColor, this);
    displayFrame(colorBox.frame);
}

function changeColor() {
    colorBox.frame = (colorBox.frame + 1) % 4;
    displayFrame(colorBox.frame)
}

function displayFrame(frame) {
    document.getElementById("frame").innerHTML = "frame = " + frame;
}


Two global variables are created, for the sprite and game. We make a sprite from the spritesheet. Frame 0 (red) is selected by default. We enable clicking on the sprite. When clicked, it recycles through another frame in range 0 to 3.


We also display the current frame in the #frame div. In the screenshot, we are at frame 3: