如何使用字母a和d移动矩形?

时间:2016-05-06 00:30:23

标签: java

当我点击左键时它向左走,当我点击右键时它向右走

 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'时它会向右走

怎么做?

2 个答案:

答案 0 :(得分:1)

VK_A用于字母A,将VK_D用于字母D.
查看official documentation了解更多信息。

  • 只能使用A和D左/右 ,只需将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;
}
  • 如果您希望能够同时使用LEFTA以及RIGHTD同时使用,请使用以下代码段:
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;
 }