java - Game loop completely freezes my program -
original question
i'm working on simple application displays map , later implement pathfinding logic units. i've implemented map , view far , runs fine until implemented game loop.
with game loop enabled, programme freezes. can't close window anymore , map isn't presented, though game loop executed fine. i've used game loop twice in past , never had problems until now.
edit: game loop continues execute fine while else freezes.
here 2 functions involved:
public gamecontroller() { paused = true; frame = new gameframe(this); map = new map(500, 500); mvm = new mapviewmodel(map.getmap(), map.getwidth(), map.getheight()); //todo: gameloop() breaks game. gameloop(); } public void gameloop() { double ticktime, lasttick; (;;) { ticktime = system.nanotime(); lasttick = ticktime; //repaints frame update(); while (ticktime - lasttick < nanoseconds_per_update) { seek { thread.sleep(1); } grab (interruptedexception ignored) {} ticktime = system.nanotime(); } } } edit2: i'm using swing. actual painting happens in paintcomponent method of gamepanel (jpanel):
@override public void paintcomponent(graphics g) { graphics2d g2 = (graphics2d) g; //paints map painter.paintmap(g2, controller.getmvm()); } obviously, if have farther questions sense free ask. in advance.
solutionhere's code i'm using now, gamecontroller , update haven't changed.
public void gameloop() { timer = new timer(milliseconds_per_update, updater); timer.start(); } updater actionlistener have added private variable class.
private actionlistener updater = new actionlistener() { @override public void actionperformed(actionevent e) { system.out.println("test2"); update(); } }; you add together updater locally prefer way.
you tell nil gui library might using, assuming might swing, looks you're running long-running code on swing event thread, main thread responsible doing swing graphics , interacting user. if so, code prevent swing redrawing gui, freezing application.
my suggestions are:
don't this. don't run long-running code on main event thread. instead consider using swing timer "game loop". or if must utilize while loop , thread sleep, off of event thread, sure swing calls mutate state of swing objects done on event thread. for more on swing threading, please read concurrency in swing. java swing freeze thread-sleep game-loop
No comments:
Post a Comment