Reputation: 2733
I am writing a simple Java
game and have ran into some problems while adding the pause/resume functionality.
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. Unfortunately, the problem is that the KeyListener
doesn't listen to the keys while in the state of being paused. How can I make it listen?
This is the KeyListener in the main classes' constructor:
this.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent evt) {
if (evt.getKeyCode() == KeyEvent.VK_P) {
isPaused = !isPaused;
}
helicopter.move(evt);
}
});
Upvotes: 0
Views: 136
Reputation: 2733
MadProgrammer solved my problem. Just make the variable isPaused
volatile.
Thanks!
Upvotes: 1