JustDown event when switching scene

Hi everyone,

I am having problem with keyboard event and scene changing.

The situation is:

  • I have 2 screens: ‘MainScene’ and ‘UIScene’.

  • In MainScene, if key ‘A’ is pressed, switch to UIScene.

  • In UIScene, if key ‘B’ is pressed, switch to MainScene.

This is an example code

class MainScene extends Phaser.Scene {
    constructor() {
        super('MainScene');
    }

    preload() {
        buttonA = this.input.keyboard.addKey('A')
    }
    create() {
        // Runs once, after all assets in preload are loaded
    }
    update() {
        if (Phaser.Input.Keyboard.JustDown(buttonA)) {
            console.log('buttonA is pressed')
            this.scene.pause('MainScene');
            this.scene.run('UIScene');
        }
    }
}

class UIScene extends Phaser.Scene {
    constructor() {
        super('UIScene');
    }
    preload() {
        // Runs once, loads up assets like images and audio
        buttonB = this.input.keyboard.addKey('B')
    }
    create() {
        // Runs once, after all assets in preload are loaded
    }
    update() {
        if (Phaser.Input.Keyboard.JustDown(buttonB)) {
            console.log('buttonB is pressed')
            this.scene.pause('UIScene');
            this.scene.resume('MainScene');
        }
    }
}
var config = {
    type: Phaser.AUTO,
    width: 800,
    height: 600,
    scene: [MainScene, UIScene]
};

var game = new Phaser.Game(config);
var buttonA = null;
var buttonB = null;

The problem occurs when switching from UIScene back to MainScene, if I press ‘A’, the JustDown event is not triggered the first time. If I press ‘A’ again, the event will be triggered.

My guess is somehow the ‘A’ key is “locked” when changing the scene.

English is not my native language so sorry for any mistakes.

Thank you for any help on this.

Neat find and great job simplifying your code down to the necessities. This definitely seems like a bug with Phaser, so I would report it here, so someone can fix it in a future version of Phaser.

1 Like

I created an issue about this problem.

I also took a look at the source code, looks like the event ‘onUp’ of the key is not fired after pressing ‘A’, so when the scene changed, the key A is ‘stuck’ as ‘Down’ state.

Temporary solution for now is adding this.buttonA.isDown=false; before changing the scene.