1

我正在用 Java Swing 创建一个简单的游戏。我有一个问题 -KeyListener似乎反应有点不稳定/缓慢。角色使用以下代码移动:

// player control
    public void keyPressed(KeyEvent e) {
        int key = e.getKeyCode();
        switch(key){
        case(KeyEvent.VK_LEFT): dx = -speed; break;
        case(KeyEvent.VK_RIGHT): dx = speed; break;
        case(KeyEvent.VK_UP): dy = -speed; break;
        case(KeyEvent.VK_DOWN): dy = speed; break;
        }
    }

public void keyReleased(KeyEvent e) {
    int key = e.getKeyCode();
    switch(key){
    case(KeyEvent.VK_LEFT): dx = 0; break;
    case(KeyEvent.VK_RIGHT): dx = 0; break;
    case(KeyEvent.VK_UP): dy = 0; break;
    case(KeyEvent.VK_DOWN): dy = 0; break;
    }
}

// this method is performed each time before redrawing the screen
public void step() {
    x += dx;
    y += dy;
}

大多数时候一切都很好,但有时角色会在对键盘做出反应之前停止一段时间。如何让键盘输入更流畅?

4

2 回答 2

1

谢谢大家的回答!他们帮助我走上正轨。

正如我在评论中所说,这里发生的情况如下:例如,如果我们按住右键 - 角色向右移动,那么我们按下左键,它开始向左移动。现在,如果我们释放右键,xSpeed 将重置为零,并且KeyListener必须等到keyPressed()再次触发,因为我们仍然按住左键。“按键重复速度”是默认设置的,据我了解无法调整。

所以解决方案是跟踪当前按下了哪些键,这样如果我们仍然按住左键,释放右键时我们不必将角色的速度降为零。

对不起,有点神秘的例子,只是试图保持代码小:

// Define keys: up, right, down, left
// 0 - not pressed, 1 - pressed
private int[] keys = {0, 0, 0, 0};

// player control
public void keyPressed(KeyEvent e) {
    int key = e.getKeyCode();
    // we set the corresponding 'key indicator' to 1 when it is pressed
    switch(key){
        case(KeyEvent.VK_LEFT): dx = -speed; keys[3] = 1; break; 
        case(KeyEvent.VK_RIGHT): dx = speed; keys[1] = 1; break;
        case(KeyEvent.VK_UP): dy = -speed; keys[0] = 1; break;
        case(KeyEvent.VK_DOWN): dy = speed; keys[2] = 1; break;
        case(KeyEvent.VK_SPACE): fireOn = true; break;
    }
}

public void keyReleased(KeyEvent e) {
    int key = e.getKeyCode();
    // now before resetting the speed we check if the opposite key
    // is still pressed
    switch(key){
        case(KeyEvent.VK_LEFT): if(keys[1]==0){dx = 0;} keys[3] = 0; break;
        case(KeyEvent.VK_RIGHT): if(keys[3]==0){dx = 0;} keys[1] = 0; break;
        case(KeyEvent.VK_UP): if(keys[2]==0){dy = 0;} keys[0] = 0; break;
        case(KeyEvent.VK_DOWN): if(keys[0]==0){dy = 0;} keys[2] = 0; break;
        case(KeyEvent.VK_SPACE): fireOn = false; break;
    }
}
于 2012-06-05T19:34:47.283 回答
1

另一种方法可能会有所帮助:

object.addKeyListener(new KeyAdapter() {
    @Override
    public void keyTyped(KeyEvent e) {
        updateOpreation();
    }

    @Override
    public void keyReleased(KeyEvent e) {
        updateOpreation();
    }

    @Override
    public void keyPressed(KeyEvent e) {
        updateOpreation();
    }

}
于 2013-05-08T23:16:55.283 回答