在android中使用openGL绘制四面体,使用不同颜色的面部,但灰色面部变形

时间:2014-03-28 13:56:36

标签: android opengl-es

package com.example.assignment1;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;

import javax.microedition.khronos.opengles.GL10;

public class Tetrahedron {

 private FloatBuffer vertexBuffer;  // Buffer for vertex-array
   private int numFaces = 4;

//color codes for 4 faces

   private float[][] colors = {  // Colors of the 4 faces
      {1.0f, 0.0f, 0.0f, 1.0f},  // 0. red
      {1.0f, 1.0f, 1.0f, 1.0f},  // 1. white
      {0.0f, 0.0f, 1.0f, 1.0f},  // 2. blue
      {0.5019f, 0.5019f, 0.5019f, 1.0f},  // 3. grey

   };

//coordinates of vertices of faces
//did i specified sequence correctly?

   private float[] vertices = {  // Vertices of the 4 faces

// FRONT Face

      -1.0f, -1.0f,  1.0f,  
       1.0f, -1.0f,  1.0f,  
      1.0f,  1.0f,  1.0f,  

//Right face

      -1.0f, -1.0f,  1.0f,  
      1.0f,  1.0f, 1.0f,
      -1.0f, -1.0f, -1.0f, 

// Left Face

       1.0f, -1.0f, 1.0f,  
      -1.0f, -1.0f, -1.0f, 
       1.0f,  1.0f, 1.0f,  

// BOTTOM

      -1.0f, -1.0f, 1.0f,  
      -1.0f, -1.0f, -1.0f, 
      1.0f, -1.0f,  1.0f  

   };

   // Constructor - Set up the buffers
   public Tetrahedron() {
      // Setup vertex-array buffer. Vertices in float. An float has 4 bytes
      ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length * 4);
      vbb.order(ByteOrder.nativeOrder()); // Use native byte order
      vertexBuffer = vbb.asFloatBuffer(); // Convert from byte to float
      vertexBuffer.put(vertices);         // Copy data into buffer
      vertexBuffer.position(0);           // Rewind
   }

// Draw the shape

   public void draw(GL10 gl) {
    gl.glFrontFace(GL10.GL_CCW);    // Front face in counter-clockwise orientation
      //gl.glEnable(GL10.GL_CULL_FACE); // Enable cull face
     gl.glCullFace(GL10.GL_BACK);    // Cull the back face (don't display)

      gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
      gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);

// Render all the faces

      for (int face = 0; face < numFaces; face++) {
         // Set the color for each of the faces
         gl.glColor4f(colors[face][0], colors[face][1], colors[face][2],       colors[face][3]);
// Draw the primitive from the vertex-array directly

         gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, face*4, 3);
      }
      gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
      gl.glDisable(GL10.GL_CULL_FACE);
   }


}

1 个答案:

答案 0 :(得分:1)

gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, face*4, 3);

应该是

gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, face*3, 3);