最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to use A, S, D, W keys in Phaser? - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question edited Oct 15, 2019 at 0:56 Manuel Abascal 6,3127 gold badges45 silver badges77 bronze badges asked Oct 14, 2019 at 20:23 btm2424btm2424 6311 gold badge10 silver badges20 bronze badges 2
  • What version of Phaser are you using? – Rojo Commented Oct 14, 2019 at 20:26
  • I'm using Phaser 3.19.0 – btm2424 Commented Oct 14, 2019 at 20:37
Add a comment  | 

2 Answers 2

Reset to default 18

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)

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

发布评论

评论列表(0)

  1. 暂无评论