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');

No comments:

Post a Comment