简体   繁体   中英

Java while loop timing

I'm making a Java game and I'm stuck on how to do timing easily. I know there's the delta time thing, but that would mean that I have to insert that delta variable in almost every movement/update function?

I was wondering if I can just time the main While loop of the game so it runs/loops every 50 miliseconds, rather then as fast as it can.

Changes in position are functions of time, so it makes sense to have to pass the time delta into most functions that update game state. It's the natural thing to do; I wouldn't be apprehensive of doing so.

While it is possible to insert delays every frame (and you almost certainly want to do so, as there's no point in having a game run at 1000 fps), it is usually detrimental to have your update logic assume that each frame will have taken a preset amount of time. Doing so results in choppiness when one frame happens to take longer than others.

To give your game a certain framerate, the general approach for each frame is as follows:

  • Record the current time as startTime .
  • Do the state updates.
  • Redraw.
  • Record the current time as endTime .
  • Sleep for (1 / framerate) - (endTime - startTime)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM