【发布时间】:2014-06-21 14:09:50
【问题描述】:
原始问题
我目前正在开发一个显示地图的简单应用程序,稍后将实现单位的寻路逻辑。到目前为止,我已经实现了地图和视图,并且在我实现游戏循环之前一切都运行良好。
启用游戏循环后,程序会冻结。即使游戏循环执行得很好,我也无法再关闭窗口并且地图没有显示。我过去曾两次使用过这个游戏循环,直到现在都没有遇到任何问题。
编辑:游戏循环继续正常执行,而其他一切都冻结了。
这里涉及到两个函数:
public GameController() {
paused = true;
frame = new GameFrame(this);
map = new Map(500, 500);
mvm = new MapViewModel(map.getMap(), map.getWidth(), map.getHeight());
//TODO: gameLoop() currently breaks the game.
gameLoop();
}
public void gameLoop() {
double tickTime, lastTick;
for (;;) {
tickTime = System.nanoTime();
lastTick = tickTime;
//Repaints the frame
update();
while (tickTime - lastTick < NANOSECONDS_PER_UPDATE) {
try {
Thread.sleep(1);
} catch (InterruptedException ignored) {}
tickTime = System.nanoTime();
}
}
}
edit2:我正在使用 Swing。实际的绘制发生在我的 GamePanel (JPanel) 的 paintComponent 方法中:
@Override
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
//Paints the map
painter.paintMap(g2, controller.getMvm());
}
显然,如果您有任何其他问题,请随时提出。提前致谢。
解决方案
这是我现在使用的代码,GameController 和更新没有改变。
public void gameLoop() {
timer = new Timer(MILLISECONDS_PER_UPDATE, updater);
timer.start();
}
updater 是我作为私有变量添加到类的 ActionListener。
private ActionListener updater = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("test2");
update();
}
};
您可以在本地添加更新程序,但我更喜欢这种方式。
【问题讨论】:
-
update() 是做什么的?
-
哦,对不起。目前它只重绘游戏框架。奇怪的是,程序在冻结其他所有内容的同时继续正常执行游戏循环。
-
感谢您的更新。 Swing 标记已添加到您的问题中。
标签: java swing freeze thread-sleep game-loop