我正在使用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;
}
大部分时间一切都很好,但有时角色会在对键盘作出反应之前停一会儿。如何使键盘输入更流畅?
答案 0 :(得分: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;
}
}
答案 1 :(得分: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();
}
}