I'm making a physics based 2D game using libGDX and Box2D. I want to move the execution of the simulation out of render thread. I use immutable messages and the BlockingQueue to pass the information about player actions. The Box2D applies forces and runs a frame of simulation. In the next step I would like to sync back the changes and update Scene2D Actors accordingly. Making an immutable copy of the state of the game world and sending it back using Gdx.app.postRunnable() is one option but it seems inefficient.

Is there any other option?


You can use an AsyncTask to run your Box2D logic. Its call method returns a result of the type you indicate when parameterizing your AsyncTask. It looks like this:

public class MyAsyncTask extends AsyncTask<Type> {

    public Type call() throws Exception {
        /* your Box2D processing goes here */
        return <new instance of Type>;

Then, you submit your task with an AsyncExecutor, like this:

final AsyncResult<Type> result = executor.submit(new MyAsyncTask());

Then, in your scene2d update method, you keep polling the task execution state, and then, when it's finished, get the result data and do something with it, in your case, update the scene2d actors:

public void update() {
    if (result.isDone()) {
        final Type data = result.get();
        /* do something with the data, eg update actors. */
    /* some other update code */

I hope this helps you.

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.