恢复游戏后,Java KeyListener事件会暂停一段时间

时间:2015-02-06 07:43:44

标签: java awt delay keylistener cardlayout

我使用KeyAdapter类进行游戏中的角色移动。这是一个代码:

    public class Keyboard extends KeyAdapter{
    private Game game;

    public Keyboard(Game game){
        this.game = game;
    }

    @Override
    public void keyPressed(KeyEvent e) {
        if(e.getKeyCode()==KeyEvent.VK_W){
            game.getPlayer().setAccelerate(0, true);
        }
        if(e.getKeyCode()==KeyEvent.VK_A){
            game.getPlayer().setAccelerate(1, true);
            System.out.println("KEY A PRESSED");
        }
        if(e.getKeyCode()==KeyEvent.VK_S){
            game.getPlayer().setAccelerate(2, true);
        }
        if(e.getKeyCode()==KeyEvent.VK_D){
            game.getPlayer().setAccelerate(3, true);
        }
        if(e.getKeyCode()==KeyEvent.VK_ESCAPE){
            game.pause();
        }
    }



    @Override
    public void keyReleased(KeyEvent e) {
        if(e.getKeyCode()==KeyEvent.VK_W){
            game.getPlayer().setAccelerate(0, false);
        }
        if(e.getKeyCode()==KeyEvent.VK_A){
            game.getPlayer().setAccelerate(1, false);
            System.out.println("KEY A RELEASED");
        }
        if(e.getKeyCode()==KeyEvent.VK_S){
            game.getPlayer().setAccelerate(2, false);
        }
        if(e.getKeyCode()==KeyEvent.VK_D){
            game.getPlayer().setAccelerate(3, false);
        }
    }

    @Override
    public void keyTyped(KeyEvent e) {}

}

点击Escape后,它会调用Game.pause():

public  void pause(){
    paused = true;
    pauseTime = System.currentTimeMillis();
    CardLayout cl = (CardLayout) cardContainer.getLayout();
    cl.show(cardContainer, "PAUSE_PANEL");

}

然后,如果用户点击RESUME,它会将游戏画布带回屏幕,请求焦点并恢复游戏。但是当我试图移动我的播放器或再次逃脱我的游戏时,KeyAdapter根本就不会抛出事件。睡了5-6秒,是什么让游戏无法播放。我该如何解决这个问题?

0 个答案:

没有答案