I am working on making a game with libGDX and I really want to thread the game so I am running a paint loop and a logic loop on separate threads much like you would making a simple java swing game with the paintcomponent loop and the runnable run loop.
I am experienced with threading in c but not so much in java.
The only way I was able to make a thread was by making a class that extends threads and then creating the run loop in there.
But the point of making the run loop was to allow each screen to compute logic freely, so I would end up needing some sort of abstractscreen class that has the custom thread class implemented.
I am asking if there is a simpler or more standard way of implementing threads for this situation.
The libGDX library already runs a separate render thread for the OpenGL context updates. See http://code.google.com/p/libgdx/wiki/TheArchitecture#The_Graphics_Module
We already learned that the UI thread is not executed continuously but only scheduled to run by the operating system if an event needs to be dispatched (roughly :p). That's why we instantiate a second thread we usually refer to as the rendering thread. This thread is created by the Graphics module that itself gets instantiated by the Application at startup.
The ApplicationListener.render()
method on your main game object will be invoked by this render thread once for every screen refresh (so it should be about 60hz), so just put the body of your render loop in your implementation of this method.
You can create an additional background thread (e.g., for game logic) in the create
method of your ApplicationListener
(be sure to clean it up in the dispose
method). Other than the render
thread, I don't think any of the pre-existing threads would be the right place for game logic.
For communication between the threads, you can use any of the existing Java synchronization approaches. I've used Java's ArrayBlockingQueue<>
to send requests to a background thread. And I've used Gdx.app.postRunnable()
to get my background threads to push data to the render thread (such Runnables are run on the next frame, before render()
is invoked).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With