0
votes

I am using this code to try to add a keyboard event to a game object. All the examples and even the Phaser API says I should add keyboard events like this:

Game.StartMenu.prototype = {

create: function () {
    startBG = this.add.image(0, 0, 'titlescreen');
    startBG.inputEnabled = true;
    startBG.events.onInputDown.addOnce(this.startGame, this);

    console.log("startBG.input: " + startBG.input);
    console.log("startBG.input.keyboard: " + startBG.input.keyboard);

    startPrompt = this.add.bitmapText(this.world.centerX-155, this.world.centerY+180, 'eightbitwonder', 'Touch to Start!', 24);
},

startGame: function (pointer) {
    this.ding.play();
    this.state.start('Game');
}

};

The "addOnce" input click listener is working. However, when I log out "startBG.input.keyboard" is just returns undefined. Why is this?

Note: Here is my preloading state as well:

Game.Preloader = function(game) {
    this.preloadBar = null;
    this.titleText = null;
    this.ready = false;
};

Game.Preloader.prototype = {

    preload: function () {
        this.preloadBar = this.add.sprite(this.world.centerX, this.world.centerY, 'preloaderBar');
        this.preloadBar.anchor.setTo(0.5, 0.5);
        this.load.setPreloadSprite(this.preloadBar);
        this.titleText = this.add.image(this.world.centerX, this.world.centerY-220, 'titleimage');
        this.titleText.anchor.setTo(0.5, 0.5);
        this.load.image('titlescreen', 'images/TitleBG.png');
        this.load.bitmapFont('eightbitwonder', 'fonts/eightbitwonder.png', 'fonts/eightbitwonder.fnt');
        this.load.image('hill', 'images/hill.png');
        this.load.image('sky', 'images/sky.png');
        this.load.atlasXML('bunny', 'images/spritesheets/bunny.png', 'images/spritesheets/bunny.xml');
        this.load.atlasXML('spacerock', 'images/spritesheets/SpaceRock.png', 'images/spritesheets/SpaceRock.xml');
        this.load.image('explosion', 'images/explosion.png');
        this.load.image('ghost', 'images/ghost.png');
        this.load.audio('explosion_audio', 'audio/explosion.mp3');
        this.load.audio('hurt_audio', 'audio/hurt.mp3');
        this.load.audio('select_audio', 'audio/select.mp3');
        this.load.audio('game_audio', 'audio/bgm.mp3');
    },

    create: function () {
        this.preloadBar.cropEnabled = false;
    },

    update: function () {
        if(this.cache.isSoundDecoded('game_audio') && this.ready == false) {
            this.ready = true;
            this.state.start('StartMenu');
        }
    }
};
1

1 Answers

0
votes

It seems that you can't attach a keyboard event listener to any old sprite or image in Phaser the way you can attach a click/tap listener. Instead, you can only attach ".input.keyboard" to the main game object. Now that I think about it, this makes sense. The keyboard inputs are sent to the the highest level object of the game, and in it's callback method one can manipulate any of the game assets depending on which key was pressed.