Use spacebar to change scene

I have this code (from codecadamy phaser course) for changing the scene and it works fine.

this.input.on('pointerup', () => {
  this.scene.stop('StartScene')
  this.scene.start('GameScene')
});

I want to use spacebar to change the scene instead but I can find out how to do it.

I have been using this to bind spacebar to functions but it is not working for this.

this.input.keyboard.on('keydown_SPACE', function (event) {
      this.scene.stop('StartScene')
      this.scene.start('GameScene')
    })

Any advice is appreciated.

Although you haven’t said anything about errors, this looks like a scope issue. Your event listener is a normal function, so its this value is different from the code around it. You can either change it to an arrow function ((event) => { instead of function (event) {) or pass this as the third argument to keyboard.on.

If this fixes your problem, I recommend reading about scope in JavaScript to avoid similar problems in the future.

2 Likes

Thank you! This the solution. I was going crazy trying to figure it out. I appriciate your reply. I wouldn’t have got there on my own. I will read what you posted so I can learn where I messed up.

I was actually listening to a youtube video recently talking about the differences between ES5 functions and ES6 arrow functions and scope and now it makes more sense.

It doesnt matter now its solved but the error message I got was

Uncaught TypeError: this.scene.stop is not a function

Thanks again :slight_smile: