How to draw a cube with bacface culling in OpenGL ES

Forum for Objective-C iPhone games and OpenGL related topics including programming doubts, books and other resources for iPhone game development

How to draw a cube with bacface culling in OpenGL ES

Postby DevelopmentTeam » Fri Oct 03, 2008 7:10 am

This is a simple example of how to draw a cube with backface culling using objective-c and OpenGL for iPhone .

Code: Select all
const GLfloat squareVertices[] = {
        // FRONT
        -0.5f, -0.5f,  0.5f,
        0.5f, -0.5f,  0.5f,
        -0.5f,  0.5f,  0.5f,
        0.5f,  0.5f,  0.5f,
        // BACK
        -0.5f, -0.5f, -0.5f,
        -0.5f,  0.5f, -0.5f,
        0.5f, -0.5f, -0.5f,
        0.5f,  0.5f, -0.5f,
        // LEFT
        -0.5f, -0.5f,  0.5f,
        -0.5f,  0.5f,  0.5f,
        -0.5f, -0.5f, -0.5f,
        -0.5f,  0.5f, -0.5f,
        // RIGHT
        0.5f, -0.5f, -0.5f,
        0.5f,  0.5f, -0.5f,
        0.5f, -0.5f,  0.5f,
        0.5f,  0.5f,  0.5f,
        // TOP
        -0.5f,  0.5f,  0.5f,
        0.5f,  0.5f,  0.5f,
        -0.5f,  0.5f, -0.5f,
        0.5f,  0.5f, -0.5f,
        // BOTTOM
        -0.5f, -0.5f,  0.5f,
        -0.5f, -0.5f, -0.5f,
        0.5f, -0.5f,  0.5f,
        0.5f, -0.5f, -0.5f,
    };
   
    [EAGLContext setCurrentContext:context];
   
    glBindFramebufferOES(GL_FRAMEBUFFER_OES, viewFramebuffer);
    glViewport(0, 0, backingWidth, backingHeight);
   
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    glEnable(GL_DEPTH_TEST); /* enable depth testing; required for z-buffer */
    glEnable(GL_CULL_FACE); /* enable polygon face culling */
    glCullFace(GL_BACK);
   
    glOrthof(-1.0f, 1.0f, -1.5f, 1.5f, -1.0f, 1.0f);
    glMatrixMode(GL_MODELVIEW);
    glRotatef(5.0f, 1.0f, 1.0f, 1.0f);
   
    glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);
   
    glVertexPointer(3, GL_FLOAT, 0, squareVertices);
    glEnableClientState(GL_VERTEX_ARRAY);

    glColor4f(1.0f, 0.0f, 0.0f, 1.0f);
    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
    glColor4f(0.5f, 0.5f, 0.0f, 1.0f);
    glDrawArrays(GL_TRIANGLE_STRIP, 4, 4);
   
    glColor4f(0.0f, 1.0f, 0.0f, 1.0f);
    glDrawArrays(GL_TRIANGLE_STRIP, 8, 4);
    glColor4f(0.0f, 0.5f, 0.5f, 1.0f);
    glDrawArrays(GL_TRIANGLE_STRIP, 12, 4);
   
    glColor4f(0.0f, 0.0f, 1.0f, 1.0f);
    glDrawArrays(GL_TRIANGLE_STRIP, 16, 4);
    glColor4f(0.5f, 0.0f, 0.5f, 1.0f);
    glDrawArrays(GL_TRIANGLE_STRIP, 20, 4);
   
    glClear(GL_DEPTH_BUFFER_BIT);
    glFlush ();
   
    glBindRenderbufferOES(GL_RENDERBUFFER_OES, viewRenderbuffer);
    [context presentRenderbuffer:GL_RENDERBUFFER_OES];
User avatar
DevelopmentTeam
Site Admin
 
Posts: 661
Joined: Tue Aug 15, 2006 8:39 am
Location: India

Return to iPhone OpenGL ES 3D Game Development Forum

Who is online

Users browsing this forum: No registered users and 2 guests

cron