我希望增加暂停/恢复游戏的可能性。 不幸的是我的解决方案只是暂停游戏,但没有恢复它(当我点击恢复按钮时没有任何反应 - 图像仍然是)。 我也尝试在thread上调用wait / notify方法,但它也没有用 - 我Exception in thread "AWT-EventQueue-0" java.lang.IllegalMonitorStateException得到了Exception in thread "AWT-EventQueue-0" java.lang.IllegalMonitorStateException 。 暂停/恢复的最佳解决方案是什么?
游戏循环
public void run() { init(); long startTime; long reTime; long waitTime; while (running) { startTime = System.nanoTime(); int CarPosX = car.zwrocPolozenieX(); int CarPosY = car.zwrocPolozenieY(); update(b, CarPosX, CarPosY); render(b); //draw(); repaint(); if(b<4390) { b=b+szybkoscMapy; } reTime = System.nanoTime() - startTime; waitTime = targetTime - reTime/100000000; try { Thread.sleep(waitTime); } catch(Exception e) { } } } public void init() { if(thread == null) { thread = new Thread(this); thread.start(); } b=0; running = true; image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB); g = (Graphics2D) image.getGraphics(); map = new Map(levelNumber); car = new Car(map); car.setxpos(338); car.setypos(150); }听众
pause_button.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { bp.running = false; } }); resume_button.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { bp.running = true; } });I want to add possibility to pause/resume to my game. Unfortunately my solution only pauses the game, but does not resume it (when I click resume button nothing happens - the image is still). I also tried to call wait/notify methods on thread, but it also did not work - I got Exception in thread "AWT-EventQueue-0" java.lang.IllegalMonitorStateException. What is the best solution to make pause/resume?
Game Loop
public void run() { init(); long startTime; long reTime; long waitTime; while (running) { startTime = System.nanoTime(); int CarPosX = car.zwrocPolozenieX(); int CarPosY = car.zwrocPolozenieY(); update(b, CarPosX, CarPosY); render(b); //draw(); repaint(); if(b<4390) { b=b+szybkoscMapy; } reTime = System.nanoTime() - startTime; waitTime = targetTime - reTime/100000000; try { Thread.sleep(waitTime); } catch(Exception e) { } } } public void init() { if(thread == null) { thread = new Thread(this); thread.start(); } b=0; running = true; image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB); g = (Graphics2D) image.getGraphics(); map = new Map(levelNumber); car = new Car(map); car.setxpos(338); car.setypos(150); }Listeners
pause_button.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { bp.running = false; } }); resume_button.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { bp.running = true; } });最满意答案
使用javax.swing.Timer来调整动画的速度。 这里将检查调用计时器的start()和stop()方法的典型控件。 使用这种Timer这种车队模拟也可能是有兴趣的。
Use javax.swing.Timer to pace the animation. Typical controls that invoke the timer's start() and stop() methods are examined here. This fleet simulation, which uses such a Timer, may also be if interest.
更多推荐
发布评论