简体   繁体   中英

Swing in game development: The game loop

I am developing Java 2D games using Swing. I run the game-loop in a thread which isn't the EDT. Most of the time there is no problem.

In my games, the only manipulation of a Swing element is to repaint() a JPanel every game loop cycle.

So my question is: Should I put the entire game-loop inside the EDT using SwingUtilities.invokeLater() ? Or should I run the game loop inside a thread which isn't the EDT?

You should not let the game logic execute on EDT as it can easily make your UI not responsive. Just let your main loop run on a separate thread and post input events there, and trigger UI repaints from that thread using the SwingUtilities .

Usually, you should not do anything on the EDT that is not directly related to painting or GUI event handling. While you technically can do this, of course, it might cause problems when the game loop becomes more complicated and has to perform more computations.

The synchronization issues that arise when you have a dedicated game thread (which executes the game loop) and the EDT come from the fact that usually the game thread will perform modifications to the game objects, and this can happen while the EDT is painting these objects. For further information, you'll have to post some example code of the entities that currently occur in your game, and how they are modified in the game loop, and how they are painted in the EDT.

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