Example 14. moveToXY

If a sprite has physics enabled, we can use moveToXY method to move it to some direction. We use mouse coordinates, from the last click to move the sprite to.


moveToXY returns angle of rotation which we can set the sprite rotation attribute to. This assumes the arrow initial state is rightwards where rotation angle is zero.


This is the javascript file which calls moveToXY in the callback to the click.



 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
// ex14. moveToXY

var GameState = {

    preload: function() {

        game.load.spritesheet("arrow", "images/arrow.png");
    },

    create: function() {

        // Set backgound color
        game.stage.backgroundColor = "#0FFF0F";

        // Start Physics
        game.physics.startSystem(Phaser.Physics.ARCADE);

        // Player centered and physics, initial left velocity
        this.player = game.add.sprite(game.world.centerX, game.world.centerY, "arrow");
        this.player.anchor.setTo(0.5);
        game.physics.enable(this.player, Phaser.Physics.ARCADE);
        this.player.body.collideWorldBounds = true;

        // move toward upperleft, and face towards it
        rot = game.physics.arcade.moveToXY(this.player, 0, 0, 100);
        this.player.rotation = rot;

        // listen to mouse click
        game.input.onDown.add(this.move, this);
    },

    move: function() {
        // move to click point, face towards it
        var x = game.input.activePointer.x;
        var y = game.input.activePointer.y;
        var rot = game.physics.arcade.moveToXY(this.player, x, y, 100);
        this.player.rotation = rot;
    }
        
};

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