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.

No comments:

Post a Comment