如何在 Phaser 中使用 A、S、D、W 键?
How to use A, S, D, W keys in Phaser?
我正在使用 Phaser.io
我想使用 A
、S
、D
、W
键。我知道您可以像这样使用箭头键:
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);
}
}
我尝试将 .left.
换成 .A.
,将 .right.
换成 .D.
,但没用。
有什么想法吗?
您可以尝试使用 Phaser.KeyCode.A
来检测正常的键盘字符。查看所有关键代码。
更新:
我找到了解决方案:
- 首先,声明将保存未来密钥的变量:
let keyA;
let keyS;
let keyD;
let keyW;
- 其次,在
create()
函数中,将key添加到对应的变量中:
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);
- 第三,让我们现在尝试按键,看看它们是否有效。在
update()
函数中,添加以下代码片段:
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')
}
您可以按每个单独的键并检查 console
消息以查看它是否被打印。
要获取所有键盘键码的列表以供将来参考:
console.log(Phaser.Input.Keyboard.KeyCodes)
我正在使用 Phaser.io
我想使用 A
、S
、D
、W
键。我知道您可以像这样使用箭头键:
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);
}
}
我尝试将 .left.
换成 .A.
,将 .right.
换成 .D.
,但没用。
有什么想法吗?
您可以尝试使用 Phaser.KeyCode.A
来检测正常的键盘字符。查看所有关键代码。
更新:
我找到了解决方案:
- 首先,声明将保存未来密钥的变量:
let keyA;
let keyS;
let keyD;
let keyW;
- 其次,在
create()
函数中,将key添加到对应的变量中:
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);
- 第三,让我们现在尝试按键,看看它们是否有效。在
update()
函数中,添加以下代码片段:
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')
}
您可以按每个单独的键并检查 console
消息以查看它是否被打印。
要获取所有键盘键码的列表以供将来参考:
console.log(Phaser.Input.Keyboard.KeyCodes)