0
我正在使用Java開發2D遊戲,不使用庫。Java - 在CardLayout中切換面板時遊戲線程會凍結
在我的遊戲InputHandler(用於移動,退出等)中,當我按下「Escape」按鈕切換到暫停菜單,然後點擊「返回」按鈕時,我的播放器不能再播放移動。
PausePanelGUI:在InputHandler
public class PausePanelGUI extends JPanel {
public PausePanelGUI(LayoutManager layout, Game game) {
super(layout);
JButton backBtn = new JButton("Back");
backBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
CardLayout c = new CardLayout();
c = (CardLayout)(GameLauncher.getMainLauncherPanel().getLayout());
c.show(GameLauncher.getMainLauncherPanel(), "Game");
game.resume();
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
backBtn.setBounds(250, 200, 150, 25);
this.add(backBtn);
}}
退出按鈕:
if (ke.getKeyCode() == KeyEvent.VK_ESCAPE) {
try {
CardLayout c = new CardLayout();
c = (CardLayout)(GameLauncher.getMainLauncherPanel().getLayout());
c.show(GameLauncher.getMainLauncherPanel(), "Pause");
game.pause();
} catch (Exception ex) {
ex.printStackTrace();
}
}
暫停和恢復方法:
public synchronized void resume() {
System.out.println("Game resumed!");
this.isPaused = false;
}
public synchronized void pause() {
System.out.println("Game paused!");
this.isPaused = true;
}
Run方法:
while (isRunning) {
if (!this.isPaused) {
long now = System.nanoTime();
delta += (now - lastTime)/nsPerTick;
lastTime = now;
boolean shouldRender = true;
while (delta >= 1) {
ticks++;
update();
delta -= 1;
shouldRender = true;
}
try {
Thread.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (shouldRender) {
frames++;
repaint();
}
if (System.currentTimeMillis() - lastTimer >= 1000) {
lastTimer += 1000;
frames = 0;
ticks = 0;
}
}
}
任何幫助? :3
你的播放器輸入代碼是什麼樣的?您是否嘗試過通過它進行調試,以查看在您取消暫停遊戲後按鍵時是否調用了它? – Sam
我沒有,我會測試,以及後輸入的代碼。 編輯:我的鑰匙沒有被取消暫停後調用:0 – Xolitude
我沒有看過你的代碼,但我認爲你不應該使用CardLayouts(因爲擺動干擾你的圖形等)。 –