OpenGL绘制带顶点的六边形

时间:2012-01-08 17:24:46

标签: android opengl-es polygon

我试图制作一个基本的形状(Hexigon)来开始并在Android平台上学习一些关于OpenGL的基础知识,我有一点问题。

我已经成功制作了一个尖头六角形,但当我将它转换为平面的Hexygon时,它无法正确渲染。这里有一些代码,供你们找出问题(可能很容易解决..)

顶点/索引

//flat hexagon
private float verticesFlat[] = {     
    0.0f,   0.0f, 0.0f,    //center
    -0.5f,   1.0f, 0.0f,    // left top
    0.5f,   1.0f, 0.0f,    // right top
    1.0f,   0.0f, 0.0f,    // right
    0.5f,   1.0f, 0.0f,    // right bottom
    -0.5f,  -1.0f, 0.0f,    // left bottom
    -1.0f,   0.0f, 0.0f,     // left
};

private short[] indices = { 0, 1, 2, 3, 4, 5, 6, 1 };

标准顶点/索引缓冲区..

// a float is 4 bytes, therefore we multiply the number if
// vertices with 4.
ByteBuffer vbb = ByteBuffer.allocateDirect(verticesFlat.length * 4);
vbb.order(ByteOrder.nativeOrder());
vertexBuffer = vbb.asFloatBuffer();
vertexBuffer.put(verticesFlat);
vertexBuffer.position(0);

// short is 2 bytes, therefore we multiply the number if
// vertices with 2.
ByteBuffer ibb = ByteBuffer.allocateDirect(indices.length * 2);
ibb.order(ByteOrder.nativeOrder());
indexBuffer = ibb.asShortBuffer();
indexBuffer.put(indices);
indexBuffer.position(0);

onDraw(GL10 gl):

gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);

gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glLoadIdentity();

GLU.gluLookAt(gl, 0, 0, -5, 0f, 0f, 0f, 0f, 1.0f, 0.0f);    

gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);

gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);
gl.glDrawElements(GL10.GL_TRIANGLE_FAN, indices.length, GL10.GL_UNSIGNED_SHORT, indexBuffer);

gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);

获得的结果如下图所示:

Wrong rendering of hexagon

1 个答案:

答案 0 :(得分:2)

应该是

private float verticesFlat[] = {     
    0.0f,   0.0f, 0.0f,    //center
    -0.5f,   1.0f, 0.0f,    // left top
    0.5f,   1.0f, 0.0f,    // right top
    1.0f,   0.0f, 0.0f,    // right
    0.5f,   -1.0f, 0.0f,    // right bottom (notice sign)
    -0.5f,  -1.0f, 0.0f,    // left bottom
    -1.0f,   0.0f, 0.0f,     // left
};