Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use A, S, D, W keys in Phaser?

I'm using Phaser.io

I would like to use A,S,D,W keys. I know that you can use arrow keys like this:

create(){
  ...
  gameState.cursors = this.input.keyboard.createCursorKeys();
}

update(){
  if (gameState.cursors.left.isDown) {
    gameState.player1.setVelocityX(-160);
  } else if (gameState.cursors.right.isDown) {
    gameState.player1.setVelocityX(160);
  }
}

I tried to switch .left. for .A. and .right. for .D. but it doesn't work.

Any ideas?

like image 547
btm2424 Avatar asked Oct 14 '19 20:10

btm2424


2 Answers

I have found a solution:

  • First, declare the variable that will hold the future keys:
let keyA;
let keyS;
let keyD;
let keyW;
  • Second, in the create() function, add the keys to the corresponding variables:
keyA = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.A);
keyS = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.S);
keyD = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.D);
keyW = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.W);
  • Third, let's try to press the keys now to see if they work. In the update() function, add the following code snippet:
if(keyA.isDown) {
   console.log('A key pressed')
} else if(keyS.isDown) {
   console.log('S key pressed')
} else if(keyD.isDown) {
   console.log('D key pressed')
} else if(keyW.isDown) {
   console.log('W key pressed')
}

You can press each individual key & check the console message to see if it gets print.

To get the list of all keyboard key codes for future reference:

console.log(Phaser.Input.Keyboard.KeyCodes)
like image 106
Manuel Abascal Avatar answered Oct 13 '22 20:10

Manuel Abascal


You could try using Phaser.KeyCode.A to detect normal keyboard characters. Have a look at to see all the key codes.

Phaser 2.4.4 - Phaser.KeyCode

Update:

Phaser 3 - Phaser.input.Keyboard.KeyCodes

like image 25
Rojo Avatar answered Oct 13 '22 20:10

Rojo