简体   繁体   English

简单的Java 2D游戏-恢复游戏

[英]Simple Java 2D game - resuming the game

I am writing a simple Java game and have ran into some problems while adding the pause/resume functionality. 我正在编写一个简单的Java游戏,在添加暂停/恢复功能时遇到了一些问题。

My main game loop looks like this: 我的主游戏循环如下所示:

    @Override
    public void run() {
        try {

        while (true) {
            if (!isPaused) {
                Thread.currentThread().sleep(5);
                diamondSpawner();
                collisionDetector();
                repaint();
            } else {

            }
        }
    } catch (InterruptedException e) {
    }
}

Additionally, I have added a KeyListener to the main class, which waits for the user to press 'P' to pause the game. 另外,我在主类中添加了一个KeyListener ,它等待用户按下“ P”来暂停游戏。 Unfortunately, the problem is that the KeyListener doesn't listen to the keys while in the state of being paused. 不幸的是,问题在于KeyListener在处于暂停状态时不会监听键。 How can I make it listen? 我该如何听呢?

This is the KeyListener in the main classes' constructor: 这是主类的构造函数中的KeyListener:

this.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent evt) {
                if (evt.getKeyCode() == KeyEvent.VK_P) {
                    isPaused = !isPaused;
                }
                helicopter.move(evt);
            }
        });

MadProgrammer solved my problem. MadProgrammer解决了我的问题。 Just make the variable isPaused volatile. 只需使isPaused变量可变isPaused Thanks! 谢谢!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM