Function to add keys

I’m brand new to phaser, just making my way through the first tutorial… so maybe getting a bit ahead of myself, but I’m trying to make adding a key easier with a function like:

const inputKey = (btn) => { return this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.btn); }

I’m not sure where I would put that function, so I tried putting it in the main scope, calling it in create, like aKey = inputKey('A'); and working with it in update, like if (cursors.left.isDown || aKey.isDown) {\\do something} but the key isn’t being assigned to anything - and there’s no error in console

Please delete - there is an error in console after all…

Arrow functions in JavaScript don’t have their own this object, so they’ll use the this object of the current scope. In the main scope, this is probably the window, which doesn’t have an input property. You’ll want to move the function in create, instead.

Your second mistake is that Phaser.Input.Keyboard.KeyCodes.btn will look for a key code named btn, not for the key code whose name matches btn's value. You should change it to Phaser.Input.Keyboard.KeyCodes[btn]. That aside, the rest of the snippets you posted should work.

Either way, you should read up on property accessors and the behavior of this in JavaScript to understand why your code doesn’t work. Additionally, it would help to know the actual error shown in the console.

1 Like

@Telinc1 - thanks. I updated the function to:

function inputKey(btn) { 
    return this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes[btn]); 
}

Thats throwing an error in console:

part1.html:59 Uncaught TypeError: Cannot read property ‘addKey’ of undefined

I also tried game.input.keyboard but still get the same error in console

inputKey.call(this, btn);
2 Likes

updated to wKey = inputKey.call(this, 'W'); - Same error

This worked for me:

function addKey (code)
{
    var key = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes[code]);

    console.log(code, key);
    console.assert(key);

    return key;
}

function create ()
{
    keyA = addKey.call(this, 'A');
    key5 = addKey.call(this, 'FIVE');
    keySpace = addKey.call(this, 'SPACE');
}