我正在用 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;
}
大多数时候一切都很好,但有时角色会在对键盘做出反应之前停止一段时间。如何让键盘输入更流畅?