Java 如何使用KeyEvent

Java how to use KeyEvent

我现在正在尝试制作游戏,但我无法找到如何通过同时按下 shift 来让玩家运行得更快。

这是我的一些代码:

public void keyPressed(KeyEvent e) {
    int key = e.getKeyCode();

    for(int i = 0; i < handler.object.size(); i++) {
        GameObject tempObject = handler.object.get(i);

        if(tempObject.getId() == ID.Player) {
            //key events for player 1
            if(key == KeyEvent.VK_W) tempObject.setVelY(-5);
            if(key == KeyEvent.VK_S) tempObject.setVelY(5);
            if(key == KeyEvent.VK_A) tempObject.setVelX(-5);
            if(key == KeyEvent.VK_D) tempObject.setVelX(5);
            if(key == KeyEvent.VK_W && key == KeyEvent.VK_SHIFT) tempObject.setVelY(-8);
            if(key == KeyEvent.VK_S && key == KeyEvent.VK_SHIFT) tempObject.setVelY(8);
            if(key == KeyEvent.VK_A && key == KeyEvent.VK_SHIFT) tempObject.setVelX(-8);
            if(key == KeyEvent.VK_D && key == KeyEvent.VK_SHIFT) tempObject.setVelX(8);
        }
    }
    if(key == KeyEvent.VK_ESCAPE) System.exit(1);
}

public void keyReleased(KeyEvent e) {
    int key = e.getKeyCode();

    for(int i = 0; i < handler.object.size(); i++) {
        GameObject tempObject = handler.object.get(i);

        if(tempObject.getId() == ID.Player) {
            if(key == KeyEvent.VK_W) tempObject.setVelY(-0);
            if(key == KeyEvent.VK_S) tempObject.setVelY(0);
            if(key == KeyEvent.VK_A) tempObject.setVelX(-0);
            if(key == KeyEvent.VK_D) tempObject.setVelX(0);
            if(key == KeyEvent.VK_W && key == KeyEvent.VK_SHIFT) tempObject.setVelY(-0);
            if(key == KeyEvent.VK_S && key == KeyEvent.VK_SHIFT) tempObject.setVelY(0);
            if(key == KeyEvent.VK_A && key == KeyEvent.VK_SHIFT) tempObject.setVelX(-0);
            if(key == KeyEvent.VK_D && key == KeyEvent.VK_SHIFT) tempObject.setVelX(0);
        }
    }
}

现在所有这些都有效,但不会将 velX 更改为 7 到 5。

实际上不能同时按下两个键。 keyPressed() 方法实际上被调用了两次(一次用于字母按钮,一次用于换档)。要检查是否按下了 shift,请将全局布尔值设置为按下 shift 的状态,并使用 keyPressed 和 keyReleased 管理变量的状态。例如:

public boolean shiftPressed;

public void keyPressed(KeyEvent e) {
    if(shiftPressed && e.getKeyCode() == VK_(a letter)) {
        //Execute some code
    }
    else if(e.getKeyCode() == VK_SHIFT) {
        shiftPressed = true;
    }
}

public void keyReleased(KeyEvent e) {
    if(e.getKeyCode() == VK_SHIFT) {
        shiftPressed = false;
    }
}