Example 13. Arrow Keys

Using createCursorKeys() method in our create() method, we can check the directions left, right, up and down arrows with isDown() in our update() method.


This program moves a sprite left, right, up or down by setting its velocity in one of the directions. Once a key is pressed and released, it will continue in that direction until new arrow key is pressed. However it will not be able to leave the world. Also it keeps changing sprite angle so it keeps facing direction it is moving.



This javascript file sets the physics and changes velocity in response to arrow keys.



 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
// ex13. Arrow Keys

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.fame = 2;
        this.player.anchor.setTo(0.5);
        game.physics.enable(this.player, Phaser.Physics.ARCADE);
        this.player.body.collideWorldBounds = true;
        this.player.body.velocity.setTo(-100,0);

        // listen to the arrow keys
        this.cursor = game.input.keyboard.createCursorKeys();
    },

    update: function() {

        // was arrow key pressed
        if(this.cursor.left.isDown) {
            this.player.body.velocity.setTo(-100, 0);
            this.player.angle = 0;
        } else if (this.cursor.right.isDown) {
            this.player.body.velocity.setTo(100, 0);
            this.player.angle = 180;
        } else if (this.cursor.up.isDown) {
            this.player.body.velocity.setTo(0, -100);
            this.player.angle = 90;
        } else if (this.cursor.down.isDown) {
            this.player.body.velocity.setTo(0, 100);
            this.player.angle = 270;
        }
    }
};

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