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.




No comments:

Post a Comment