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:


No comments:

Post a Comment