swing - Strange behavior of java game loop -
i have simple game loop in java:
public void run(){ while(running){ start = system.nanotime(); gamepanel.update(); gamepanel.repaint(); elapsed = system.nanotime() - start; wait = (target_time - elapsed) / 1000000; if(wait < 0){wait = target_time;} try {thread.sleep(wait);}catch(exception e) {e.printstacktrace();} } }
now problem: when add sysout in update() outing "updating" , 1 in paintcomponent() outing "repainting", following result:
updating updating updating updating updating (x1000 , more) repainting
so when repaint 1 time, game updating 1000 , more times. normal? think abit strange, isnt it? example can 1000 steps player until game painting it... means, update() method doesnt wait repaint finishing? why?
thank you!
edit: here update code:
public void update(){ if(moveup){ changemapy(map, -map.getspeed()); } if(movedown){ changemapy(map, map.getspeed()); } if(moveright){ changemapx(map, map.getspeed()); } if(moveleft){ changemapx(map, -map.getspeed()); } }
edit 2: , changemap does: (maybe problem?)
public void changemapx(map map, int amount){ for(int = 0; < blocks.length; i++){ for(int j = 0; j < blocks[0].length; j++){ blocks[i][j].addx(amount); } } map.addoffsetx(amount); } public void changemapy(map map, int amount){ for(int = 0; < blocks.length; i++){ for(int j = 0; j < blocks[0].length; j++){ blocks[i][j].addy(amount); } } map.addoffsety(amount); }
you calculate wait in seconds. (nano-seconds / 1 million)
the parameter sleep should in miliseconds. change line:
wait = (target_time - elapsed) / 1000;
Comments
Post a Comment