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.

No comments:

Post a Comment