Phaser3 + ES6 Classes : How To Keep The Scope From Create To Update
I'm a beginner in Phaser 3 dev and I'm trying to define a good pattern for all my games. I found a lot of excellent one-page tutorials but when I translate them in the ES6 classes system, I'm having a hard time with scope issue (elements defined in create() aren't visible in update).
I've seen that one common pattern without ES6 classes is to add the methods in the scene property of the game config object like this :
scene: {
preload: preload,
create: create,
update : update
}
Now here's my question. If I have this code :
window.onload = function() {
const config = {
width: 1136,
height: 640,
backgroundColor: "#ECF0F1",
scene: bootGame
}
jeu = new Phaser.Game(config);
class bootGame extends Phaser.Scene{
constructor(){
super("BootGame");
}
preload(){}
create(){
let cursors = this.input.keyboard.createCursorKeys();
}
update(){
if (cursors.left.isDown){// cursors not defined}
}
}
What should I write to get "cursors" to be defined in update() ?
Many thanks for your help!
PS: I've seen that question Phaser + Typescript losing scope in update but it's Typescript + import module syntax gets me lost in the way.
Answer
bootGame
is class and in class this
refers to that class. So, you need to create this.cursors
so it becomes the property of that class and every method(function) in the same class can access that property by this.cursors
.
When you define variable with let
it's scope is limited to the block it is defined in. Here, you have defined cursors
in create
function so it cannot be accessed outside create
function.
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM