简体   繁体   中英

Can't load tiledmap within thread without it glitching(libgdx)

So if I have the code arranged like this(Inside a screen):

private TiledMap m = new Tmxloader.load("map");
private OrthogonalTiledMapRenderer renderer = new OrthogonalTiledMapRenderer(m);

public void render(float delta) {

    renderer.setView(cam); 
    renderer.render();

}

It works perfectly fine. The map is loaded, rendered, and there is no problem.

But when I put the loading of the map in a thread to reduce load time...

private TiledMap m;
private OrthogonalTiledMapRenderer renderer;
private boolean loaded = false;

new Thread(new Runnable() {
        @Override
        public void run() {
            m = new Tmxloader.load("map");
            loaded = true;
        }
    }).start(); 

if(loaded){
    renderer = new OrthogonalTiledMapRenderer(m);
}

public void render(float delta) {

    renderer.setView(cam); 
    renderer.render();

}

The map renders incorrectly. In fact, I wouldn't even call it the map rendering at this point. All I see is some gray circles. I've tried everything and can't find a way around it.

(This isn't my excact code, you might say I don't need to load the map in a thread here, but in my game I do. Trust me.)

According to doc :

In Libgdx only one thread (the thread that executes the app lifecycle callbacks) has a valid OpenGL context and can invoke OpenGL calls. You can post a Runnable to the GDX thread from your other threads to get it to execute stuff on behalf of other threads. Posted runnables will be executed before the next render callback is run. See Gdx.app.postRunnable()


If loading time is the issue then you should use AssetManager for your requirement and show loading screen when all your resource are loading.

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