在libgdx中,一般的逻辑流程都在rende()函数中执行,这个函数是由opengl的渲染线程调用的,一般的图形显示和逻辑处理都在这个线程中。
一般情形下,在这个线程中处理就行了。但是当某些逻辑处理比较费时,可能会引起画面卡顿、不连贯等现象。这时,可以将主要的逻辑处理放在另一个线程中,然后再即将进行图形渲染时再将其传送到render线程中执行。
回传采用Gdx.app.postRunnable()函数,该函数调用后,回传的那部分代码会在下一次render()函数调用之前执行。
具体实例:
package com.fxb.newtest; import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.utils.Array; public class Lib020_Thread extends ApplicationAdapter{ float currentTime;
//float lastTime; SpriteBatch batch;
BitmapFont font;
int count = 0; Array<TextureRegion> array1 = new Array<TextureRegion>(); Thread thread = new Thread(){
@Override
public void run() {
// TODO Auto-generated method stub
//final int a = 2; try{
while(true)
{
Thread.sleep( 1000 );
count++; if( count == 3 ){
Gdx.app.postRunnable(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
TextureRegion region = new TextureRegion( new Texture( Gdx.files.internal( "data/pal4_1.jpg" ) ) );
array1.add( region );
}
});
}
if( count == 5 ){
Gdx.app.postRunnable(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
TextureRegion region = new TextureRegion( new Texture( Gdx.files.internal( "data/badlogic.jpg" ) ) );
array1.add( region );
}
});
}
}
}
catch(Exception e){
e.printStackTrace();
}
}
}; @Override
public void create() {
// TODO Auto-generated method stub
super.create(); batch = new SpriteBatch();
font = new BitmapFont();
font.setColor( Color.BLACK ); thread.start(); //array1.add( new TextureRegion( new Texture( Gdx.files.internal( "data/badlogic.jpg" ) ) ) );
} @Override
public void render() {
// TODO Auto-generated method stub
super.render();
Gdx.gl.glClearColor( 1, 1, 1, 1 );
Gdx.gl.glClear( GL10.GL_COLOR_BUFFER_BIT ); batch.begin(); float width = 0;
for( int i=0; i<array1.size; ++i ){
batch.draw( array1.get(i), width, 0 );
width += array1.get(i).getRegionWidth()+5;
}
font.draw( batch, ""+count, 100, 280 );
batch.end(); } @Override
public void dispose() {
// TODO Auto-generated method stub
super.dispose();
font.dispose();
batch.dispose();
} }
运行效果:
刚开始没有加入图片纹理区域:
第3秒后加入第一幅图片纹理区域:
第5秒加入第二幅图片纹理区域:
当某些逻辑运算或资源加载比较费时时,可以考虑多线程方式。