Pro OpenGL ES for iOS

(singke) #1

60 CHAPTER 3: Building a 3D World^


Going Beyond the Bouncy Square

Now let’s change the preceding example to add a third dimension. Because we’re
getting seriously 3D here, several things will need to be added to handle the Z
dimension, including a larger dataset for the cube’s geometry and color, methods of
handing off that data to OpenGL, the frustum definition, any face culling techniques if
needed, and rotations instead of just the translations.

Note Translation means to move an object around in your world up/down, left/right, and
forward/backward, while rotation means to rotate the object and any arbitrary axis. Both are
considered transformations.

Adding the Geometry


Now we need to double the number of vertices from the above example and extend
them to support the extra z-value as shown in line 1 of Listing 3-3. You’ll notice that all
of the vertices are either .5 or -.5. Previously values for the Y-axis were -0.33 to 0.33.
That compensated for the aspect ratio of the screen, stretching out the image so that
the square really does look square. In this exercise, the viewing frustum will be added,
which will enable us to specify the aspect ratio so that we don’t have to compensate for
non-square screens.
Following that, the color array is likewise doubled in size (lines 2ff). Then we need to
specify how the vertices are all tied together so as to make 6 square faces out of 12
triangles. That is done via two additional arrays called tfan1 and tfan2. The numbers are
indices into the vertex array, telling the system how to tie which points together in a form
known as a ‘‘triangle fan.’’ This will be covered shortly. So you will now be modifying the
bouncy square app, either by using the original or just making a copy.

Note You can rename an Xcode 4 project by going to the root of the project and renaming
the project name at the very top of the tree. Unfortunately, it doesn’t get everything like source
files or references in the .xib files, so you’ll still have to change those manually.

When ready, swap out the 2D data definitions in drawInRect()for the 3D-ified versions
shown in Listing 3-3.
Free download pdf