1. 程式人生 > >android遊戲開發(OpenGL ES繪製矩形平面)

android遊戲開發(OpenGL ES繪製矩形平面)

接觸android將近一年了,以前學的應用開發,現在自學android遊戲開發,把自己學到的分享出來一下,(這也是我的第一篇部落格),不說廢話了,開始正文:

GLRender類用於圖形的渲染工作,Util類用於glrender中的資料緩衝。

GLRender類:

package com.example.xu.vertexdraw;
public class GLRender implements GLSurfaceView.Renderer {
    public float xrot;
    public float yrot;
    public float zrot;
//定義頂點緩衝
private FloatBuffer _vertexsBuffer; //定義頂點緩衝 private FloatBuffer _vertexsBUffer; //定義索引緩衝 private ByteBuffer _indicesBuffer; public void onSurfaceCreated(GL10 gl,EGLConfig config){ //啟用陰影平滑 gl.glShadeModel(GL10.GL_SMOOTH); //黑色背景 gl.glClearColor(0,0,0,0); //設定深度快取 gl.glClearDepthf(1.0f); //啟用深度測試 gl.glEnable(GL10.GL_DEPTH_TEST
); //所做深度測試的內容 gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT,GL10.GL_FASTEST); //建立頂點資料 float vertexs[] = new float[12]; vertexs[0] = 1.0f; vertexs[1] = 1.0f; vertexs[2] = 0.0f; vertexs[3] = -1.0f; vertexs[4] = 1.0f; vertexs[5] = 0.0f; vertexs[6] = -1.0f; vertexs[7] = -1.0f; vertexs[8] = 0.0f; vertexs[9] = 1.0f; vertexs[10
] = -1.0f; vertexs[11] = 0.0f; //建立索引資料 byte indices[] = new byte[6]; indices[0] = 0; indices[1] = 1; indices[2] = 2; indices[3] = 0; indices[4] = 2; indices[5] = 3; //建立頂點緩衝 this._vertexsBuffer = Util.getFloatBuffer(vertexs); //建立索引緩衝 this._indicesBuffer = Util.getByteBUffer(indices); } public void onDrawFrame(GL10 gl){ //清除螢幕和深度快取 gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); //重置當前的模型觀察矩陣 gl.glLoadIdentity(); //重置當前的模型觀察矩陣 gl.glLoadIdentity(); //移入螢幕的一段距離 gl.glTranslatef(0.0f,0.0f,-3.0f); //設定三個方向的旋轉 gl.glRotatef(xrot,1.0f,0.0f,0.0f); gl.glRotatef(yrot,0.0f,1.0f,0.0f); gl.glRotatef(zrot,0.0f,0.0f,1.0f); //允許設定頂點 gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glVertexPointer(3,GL10.GL_FLOAT,0,this._vertexsBuffer); //索引繪製法 gl.glDrawElements(GL10.GL_TRIANGLES,6,GL10.GL_UNSIGNED_BYTE,this._indicesBuffer); //取消頂點設定 gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); //結束繪製 gl.glFinish(); } public void onSurfaceChanged(GL10 gl,int width,int heigth){ float ratio = (float) width / heigth; //設定opengl場景的大小 gl.glViewport(0,0,width,heigth); //設定投影矩陣 gl.glMatrixMode(GL10.GL_PROJECTION); //重置投影矩陣 gl.glLoadIdentity(); //設定視口大小 gl.glFrustumf(-ratio,ratio,-1,1,1,10); //選擇模型觀察矩陣 gl.glMatrixMode(GL10.GL_MODELVIEW); //重置模型觀察矩陣 gl.glLoadIdentity(); } }

Util類:

public class Util {
    public static FloatBuffer getFloatBuffer(float[] vertexs) {
        FloatBuffer buffer;
ByteBuffer qbb = ByteBuffer.allocateDirect(vertexs.length * 18);
qbb.order(ByteOrder.nativeOrder());
buffer = qbb.asFloatBuffer();
buffer.put(vertexs);
buffer.position(0);
        return buffer;
}

    public static ByteBuffer getByteBUffer(byte[] indices) {
        ByteBuffer buffer = null;
buffer = ByteBuffer.allocateDirect(indices.length);
buffer.put(indices);
buffer.position(0);
        return buffer;
}
}

還需新建MySurfaceView類用於獲取使用者輸入,實現人機互動。

(求大神勿噴,第一次寫)