第五课 3D空间:
我们使用多边形和四边形创建3D物体,在这一课里,我们把三角形变为立体的金子塔形状,把四边形变为立方体。
先看看三角形的顶点变成啥了
private float[] mTriangleArray = { 0.0f,1.0f,0.0f, -1.0f,-1.0f,1.0f, 1.0f,-1.0f,1.0f, 0.0f,1.0f,0.0f, 1.0f,-1.0f,1.0f, 1.0f,-1.0f,-1.0f, 0.0f,1.0f,0.0f, 1.0f,-1.0f,-1.0f, -1.0f,-1.0f,-1.0f, 0.0f,1.0f,0.0f, -1.0f,-1.0f,-1.0f, -1.0f,-1.0f,1.0f }; private FloatBuffer mTriangleBuffer;
一个四个面,每个面三个点,地面没画。
你们仔细看看每个面,都是按逆时针方向画的。当然,如果你没有增加Cull剔除代码(上节课最后提到),至于顺时针,逆时针都无所谓,都画。但是我们还是推荐使用按照方向来写的array。
三角形的颜色数组来了
private float[] mColorArray={ 1.0f,0.0f,0.0f,1.0f, 0.0f,1.0f,0.0f,1.0f, 0.0f,0.0f,1.0f,1.0f, 1.0f,0.0f,0.0f,1.0f, 0.0f,0.0f,1.0f,1.0f, 0.0f,1.0f,0.0f,1.0f, 1.0f,0.0f,0.0f,1.0f, 0.0f,1.0f,0.0f,1.0f, 0.0f,0.0f,1.0f,1.0f, 1.0f,0.0f,0.0f,1.0f, 0.0f,0.0f,1.0f,1.0f, 0.0f,1.0f,0.0f,1.0f, }; private FloatBuffer mColorBuffer;
注意,同一个点是同一个颜色。
立方体的顶点数组:(原文中没有)
// 四边形的顶点数组
private float[] mQuadsArray = {
// 前
1f, 1f, 1f, // 右上
-1f, 1f, 1f, // 左上
-1f, -1f, 1f, // 左下
1f, -1f, 1f,// 右下
// 右
1f, 1f, -1f, // 右上
1f, 1f, 1f, // 左上
1f, -1f, 1f, // 左下
1f, -1f, -1f,// 右下
// 后
-1f, 1f, -1f, // 右上
1f, 1f, -1f, // 左上
1f, -1f, -1f, // 左下
-1f, -1f, -1f,// 右下
// 左
-1f, 1f, 1f, // 右上
-1f, 1f, -1f, // 左上
-1f, -1f, -1f, // 左下
-1f, -1f, 1f, // 右下
// 顶
1f, 1f, -1f, // 右上
-1f, 1f, -1f, // 左上
-1f, 1f, 1f, // 左下
1f, 1f, 1f, // 右下
// 底
1f, -1f, 1f, // 右上
-1f, -1f, 1f, // 左上
-1f, -1f, -1f, // 左下
1f, -1f, -1f // 右下
}; // 从这里可以看出,我们按照逆时针的方向画图
private FloatBuffer mQuadsBuffer;
立方体的颜色数组来了
private float[] mQuadColorArray={ 0.0f,1.0f,0.0f,1.0f, 0.0f,1.0f,0.0f,1.0f, 0.0f,1.0f,0.0f,1.0f, 0.0f,1.0f,0.0f,1.0f, 1.0f,0.5f,0.0f,1.0f, 1.0f,0.5f,0.0f,1.0f, 1.0f,0.5f,0.0f,1.0f, 1.0f,0.5f,0.0f,1.0f, 1.0f,0.0f,0.0f,1.0f, 1.0f,0.0f,0.0f,1.0f, 1.0f,0.0f,0.0f,1.0f, 1.0f,0.0f,0.0f,1.0f, 1.0f,1.0f,0.0f,1.0f, 1.0f,1.0f,0.0f,1.0f, 1.0f,1.0f,0.0f,1.0f, 1.0f,1.0f,0.0f,1.0f, 0.0f,0.0f,1.0f,1.0f, 0.0f,0.0f,1.0f,1.0f, 0.0f,0.0f,1.0f,1.0f, 0.0f,0.0f,1.0f,1.0f, 1.0f,0.0f,1.0f,1.0f, 1.0f,0.0f,1.0f,1.0f, 1.0f,0.0f,1.0f,1.0f, 1.0f,0.0f,1.0f,1.0f, }; private FloatBuffer mQuadColorBuffer;
不要晕,后面有了纹理就好了,不过这是基础,一定要掌握。
画图的代码来了
gl.glTranslatef(-1.5f, 0.0f, -6.0f);
gl.glRotatef(rtri, 0.0f, 1.0f, 0.0f); //绕Y轴旋转
// gl.glColor4f(1f, 1f, 1f, 1f);
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glEnableClientState(GL10.GL_COLOR_ARRAY); gl.glColorPointer(4, GL10.GL_FLOAT, 0, mColorBuffer); gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mTriangleBuffer);
gl.glDrawArrays(GL10.GL_TRIANGLES, 0, 12); //四棱锥有4个面,每个面3个点 gl.glLoadIdentity();
gl.glTranslatef(1.5f, 0.0f, -6.0f);
gl.glRotatef(rquad, 1.0f, 0.0f, 0.0f); // gl.glRotatef(rquad, 1.0f, -0.8f, 0.0f); // 斜着旋转 gl.glColorPointer(4, GL10.GL_FLOAT, 0, mQuadColorBuffer);
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mQuadsBuffer); //依次画6个面
for (int i=0; i<6; i++){
gl.glDrawArrays(GL10.GL_TRIANGLE_FAN, i*4, 4);
} rtri+=0.2f;
rquad-=0.15f;
运行结果:
(注:本教程转自其他网页,并加以修改,查看原网页请点击这里)