当我点击左键时它向左走,当我点击右键时它向右走
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT)
xa = -game.speed;
if (e.getKeyCode() == KeyEvent.VK_RIGHT)
xa = game.speed;
}
我想知道用'a'和'd'做同样的事情。
所以当我点击'a'时它会向左走,当我点击'd'时它会向右走
怎么做?
答案 0 :(得分:1)
将VK_A
用于字母A,将VK_D
用于字母D.
查看official documentation了解更多信息。
VK_LEFT
替换为VK_A
,将VK_RIGHT
替换为VK_D
,如下面的代码:
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_A)
xa = -game.speed;
else if (e.getKeyCode() == KeyEvent.VK_D)
xa = game.speed;
}
LEFT
和A
以及RIGHT
和D
同时使用,请使用以下代码段:
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_LEFT || keyCode == KeyEvent.VK_A)
xa = -game.speed;
else if (keyCode == KeyEvent.VK_RIGHT || keyCode == KeyEvent.VK_D)
xa = game.speed;
}
答案 1 :(得分:1)
添加到您的代码中:
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT || e.getKeyCode() == KeyEvent.VK_A)
xa = -game.speed;
if (e.getKeyCode() == KeyEvent.VK_RIGHT || e.getKeyCode() == KeyEvent.VK_D)
xa = game.speed;
}