Game Development Reference
In-Depth Information
model-view matrix and load an identity matrix. We call this method each frame so that we
can start from a clean slate. No more direct OpenGL ES calls to set up our viewport and
projection matrix.
public void touchToWorld(Vector2 touch) {
touch.x = (touch.x / ( float ) glGraphics.getWidth()) * frustumWidth * zoom;
touch.y = (1 - touch.y / ( float ) glGraphics.getHeight()) * frustumHeight * zoom;
touch.add(position).sub(frustumWidth * zoom / 2, frustumHeight * zoom / 2);
}
}
The touchToWorld() method takes a Vector2 instance containing touch coordinates and
transforms the vector to world space. This is the same as was just discussed; the only difference
is that we can use our fancy Vector2 class.
An Example
We'll now use the Camera2D class in your cannon example. Copy the CollisionTest file and
rename it Camera2DTest . Rename the GLGame class inside the file Camera2DTest , and rename the
CollisionScreen class Camera2DScreen . There are a few little changes we have to make to use
our new Camera2D class.
The first thing we do is add a new member to the Camera2DScreen class:
Camera2D camera;
We initialize this member in the constructor, as follows:
camera = new Camera2D(glGraphics, WORLD_WIDTH, WORLD_HEIGHT);
We pass in our GLGraphics instance and the world's width and height, which we previously used
as the frustum's width and height in our call to glOrthof() . All we need to do now is replace our
direct OpenGL ES calls in the present() method, which looked like this:
gl.glViewport(0, 0, glGraphics.getWidth(), glGraphics.getHeight());
gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glLoadIdentity();
gl.glOrthof(0, WORLD_WIDTH, 0, WORLD_HEIGHT, 1, -1);
gl.glMatrixMode(GL10.GL_MODELVIEW);
We replace them with this:
gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
camera.setViewportAndMatrices();
We still have to clear the framebuffer, of course, but all the other direct OpenGL ES calls are
nicely hidden inside the Camera2D.setViewportAndMatrices() method. If you run that code, you'll
see that nothing has changed. Everything works like before—all we did was make things a little
nicer and more flexible.
 
Search WWH ::




Custom Search