其實畫三角體很簡單,就是有四個三角形組成的,所以會畫三角形就會畫三角體了,最好是自己先研究一下再看代碼,其實不難,試試吧
package wyf.swq;
import java.nio.ByteBuffer; //引人相關包
import java.nio.ByteOrder; //引人相關包
import java.nio.IntBuffer; //引人相關包
import javax.microedition.khronos.opengles.GL10; //引人相關包
public class TrianglePair {
private IntBuffer myVertexBuffer; //頂點座標資料緩衝
private IntBuffer myColorBuffer; //頂點著色資料緩衝
private ByteBuffer myIndexBuffer; //頂點索引資料緩衝
int vCount=0; //頂點數量
int iCount=0; //索引數量
float yAngle=0; //繞y軸旋轉的角度
float zAngle=0; //繞z軸旋轉的角度
public TrianglePair(){
vCount=4; //一個三角形,3個頂點
final int UNIT_SIZE=10000; //縮放比例
int []vertices=new int[]{
0,0,0,
8*UNIT_SIZE,0,0,
0,8*UNIT_SIZE,0,
0,0,8*UNIT_SIZE
// 8*UNIT_SIZE,10*UNIT_SIZE,0,
// 2*UNIT_SIZE,10*UNIT_SIZE,0
};
//建立頂點座標資料緩衝,由於不同平台位元組順序不同,資料單元不是位元組的(上面的事整型的緩衝),一定要經過ByteBuffer轉換,關鍵是通過ByteOrder設定nativeOrder()
ByteBuffer vbb=ByteBuffer.allocateDirect(vertices.length*4);//分配的記憶體塊
vbb.order(ByteOrder.nativeOrder());//設定本地平台的位元組順序
myVertexBuffer=vbb.asIntBuffer();//轉換為int型緩衝
myVertexBuffer.put(vertices);//向緩衝區中放入頂點座標資料
myVertexBuffer.position(0);//設定緩衝區的起始位置
final int one=65535;//支援65535色色彩通道
int []colors=new int[]{//頂點顏色值數組,每個頂點4個色彩值RGBA
one,one,one,0,
0,0,one,0,
0,0,one,0,
one,one,one,0,
one,0,0,0,
one,0,0,0
};
ByteBuffer cbb=ByteBuffer.allocateDirect(colors.length*4); //分配的記憶體塊
cbb.order(ByteOrder.nativeOrder()); //設定本地平台的位元組順序
myColorBuffer=cbb.asIntBuffer(); //轉換為int型緩衝
myColorBuffer.put(colors); //向緩衝區中放入頂點顏色資料
myColorBuffer.position(0); //設定緩衝區的起始位置
//為三角形構造索引資料初始化
iCount=12;
byte []indices=new byte[]{
0,1,2,
0,1,3,
0,2,3,
1,2,3
};
//建立三角形構造索引資料緩衝
myIndexBuffer=ByteBuffer.allocateDirect(indices.length); //分配的記憶體塊
myIndexBuffer.put(indices); //向緩衝區中放入頂點索引資料
myIndexBuffer.position(0); //設定緩衝區的起始位置
}
public void drawSelf(GL10 gl){
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);//啟用頂點座標數組
gl.glEnableClientState(GL10.GL_COLOR_ARRAY);//啟用頂點顏色數組
gl.glRotatef(yAngle,0,1,0);//根據yAngle的角度值,繞y軸旋轉yAngle
gl.glRotatef(zAngle,0,0,1);
gl.glVertexPointer( //為畫筆指定頂點座標資料
3, //每個頂點的座標數量為3
GL10.GL_FIXED, //頂點座標值的類型為GL_FIXED,整型
0, //連續頂點座標資料之間的間隔
myVertexBuffer //頂點座標數量
);
gl.glColorPointer(//為畫筆指定頂點 顏色資料
4,
GL10.GL_FIXED,
0,
myColorBuffer
);
gl.glDrawElements(//繪製圖形
GL10.GL_TRIANGLES, //填充模式,這裡是以三角形方式填充
iCount, //
GL10.GL_UNSIGNED_BYTE, //開始點編號
myIndexBuffer //頂點數量
);
}}