Game Development Reference
In-Depth Information
Previously, we used glOrthof() to specify the orthographic view frustum in the form of a
projection matrix. For the perspective view frustum, we could use a method called glFrustumf() .
However, there's an easier way.
Traditionally, OpenGL ES comes with a utility library called GLU . It contains a couple of helper
functions for things like setting up projection matrices and implementing camera systems.
That library is also available on Android in the form of a class called GLU . It features a few static
methods we can invoke without needing a GLU instance. The method in which we are interested
is called gluPerspective() :
GLU.gluPerspective(GL10 gl, float fieldOfView, float aspectRatio, float near, float far);
This method will multiply the currently active matrix (that is, the projection matrix or the model-
view matrix) with a perspective projection matrix, similar to glOrthof() . The first parameter
is an instance of GL10 , usually the one used for all other OpenGL ES-related business; the
second parameter is the field of view, given in angles; the third parameter is the aspect ratio
of the viewport; and the last two parameters specify the distance of the near and far clipping
planes from the camera position. Since we don't have a camera yet, those values are given
relative to the origin of the world, forcing us to look down the negative z axis, as shown in
Figure 10-4 . That's totally fine for our purposes at the moment; we will make sure that all the
objects we render stay within this fixed and immovable view frustum. As long as we only use
gluPerspective() , we can't change the position or orientation of our virtual camera. We will
always only see a portion of the world when looking down the negative z axis.
Let's modify Listing 10-2 so that it uses perspective projection. First, just copy over all code
from Vertices3Test to a new class called PerspectiveTest , and also rename Vertices3Screen
to PerspectiveScreen . The only thing we need to change is the present() method. Listing 10-3
shows the code.
Listing 10-3. Excerpt from PerspectiveTest.java; Perspective Projection
@Override
public void present( float deltaTime) {
GL10 gl = glGraphics.getGL();
gl.glClear(GL10. GL_COLOR_BUFFER_BIT );
gl.glViewport(0, 0, glGraphics.getWidth(), glGraphics.getHeight());
gl.glMatrixMode(GL10. GL_PROJECTION );
gl.glLoadIdentity();
GLU. gluPerspective (gl, 67,
glGraphics.getWidth() / ( float )glGraphics.getHeight(),
0.1f, 10f);
gl.glMatrixMode(GL10. GL_MODELVIEW );
gl.glLoadIdentity();
vertices.bind();
vertices.draw(GL10. GL_TRIANGLES , 0, 6);
vertices.unbind();
}
The only difference from the present() method in the previous example is that we are now using
GLU.gluPerspective() instead of glOrtho() . We use a field of view of 67 degrees, which is close
 
Search WWH ::




Custom Search