Android遊戲之GLSurfaceView

Android遊戲之GLSurfaceView

遊戲設計中通常『更新』『渲染』放在同一線程中.在Windows可以在主線程將『消息驅動』改為『實時驅動』.把『更新』『渲染』放在主線程中.而Android卻無法做到這點.但提供GLSurfaceView可建立獨立線程在背後實現『更新』『渲染』.你需要實現監聽接口GLSurfaceView.Renderer.並註冊到GLSurfaceView中.監聽接口需要分別重寫『創建』『調整大細』『渲染』.GLSurfaceView.Renderer可獲得GL10.通過它方可訪問OpenGL ES API.而GL10中10代表OpenGL ES 1.0標準.可以將GLSurfaceView封裝成獨立控件.從而在layout『佈局』中嵌入.

public class RenderView extends GLSurfaceView implements GLSurfaceView.Renderer {

每當Activity恢復或啟動創建. EGLConfig設置Surface顏色與深度

public void onSurfaceCreated(GL10 gl10, EGLConfig eglConfig);

當view尺寸發生改變時調用,傳入寬與高

public void onSurfaceChanged(GL10 gl10, int width, int height);

調用『渲染』『更新』完成幀繪製.但每秒不超過60幀.

public void onDrawFrame(GL10 gl10);

令外還需重寫『恢復』『暫停』

『恢復』重啟渲染線程,在Activity恢復顯示時在Activity.onResume()中調用

public void onResume();

『暫停』退出渲染線程,當Activity進入後臺時在Activity.onPause()中調用

public void onPause();

}

編輯layout『佈局』文檔main.xml添加

<net.bookcard.aa.RenderView

android:id=”@+id/render_view”

android:layout_width=”fill_parent”

android:layout_height=”fill_parent” />

定義view狀態

public static final int       STATE_INIT       = 0;// 初此

public static final int  STATE_RUN       = 1;// 運行

public static final int  STATE_PAUSED    = 2;// 暫停

public static final int  STATE_FINISHED  = 3;// 結束

public static final int  STATE_IDLE       = 4;// 閒置

int view_width,view_height;// 寬與高

int state = STATE_INIT;// 初此狀態

long    startTime ;// 啟動時間

創建Surface獲取屏幕

public void onSurfaceCreated(GL10 gl, EGLConfig eglConfig){

SCREEN  screen = GAME.getCurrentScreen();// 當前屏幕

if(state == STATE_INIT) {// 初此

Init(gl, this);

screen = GAME.getMainScreen();

GAME.setCurrentScreen(screen);

}

else {//  重新載入資源

ASSETS.reload();

}

screen = GAME.getCurrentScreen();

state = STATE_RUN;// 運行

startTime = System.nanoTime();// 獲取啟動時間

}

大小發生改變

public void onSurfaceChanged(GL10 gl, int width, int height){

this.view_width = width;// 寬

this.view_height = height;// 高

}

更新並渲染.System.nanoTime()返回納秒, 1000000000納秒=1秒.通過兩次時間測量計算間隔時間

public void onDrawFrame(GL10 gl){

SCREEN screen = GAME.getCurrentScreen();

if(state == STATE_RUN){// 運行

float deltaTime = (System.nanoTime()-startTime) / 1000000000.0f;

startTime = System.nanoTime();// 獲取當前時間

screen.update(deltaTime);// 更新

screen.present(deltaTime);// 渲染

}

else

if(state == STATE_PAUSED) {// 暫停

screen.pause();

}

else

if(state == STATE_FINISHED) {// 結束

screen.pause();

screen.dispose();

}

}

恢復渲染在Activity.onResume()中調用

public void onResume(){

super.onResume();

MUSIC.Resume();

}

暫停渲染在Activity.onPause()中調用

public void onPause(){

state = STATE_PAUSED;// 暫停

super.onPause();

MUSIC.Pause();

}

初此遊戲系統個部件

void Init(GL10 gl, GLSurfaceView view){

GRAPHICS.Init(gl,view);

SYSTEM.Init(context);// 系統

FileIO.Init(context);// 文件讀寫

BITMAP.Init(context);// 位圖

SOUND.Init(context,100);// 聲音

MUSIC.Init(context,100);// 音樂

TOUCH.Init(this);// 觸摸模塊

GAME.Init();//  屏幕切換系統

BATCHER.Init(1500);// 精靈批處理

ASSETS.load();// 資源

}

評論