Game Development Reference
In-Depth Information
Listing 8-15. Camera2D.java, Our Shiny New Camera Class for 2D Rendering
package
com.badlogic.androidgames.framework.gl;
import
javax.microedition.khronos.opengles.GL10;
import
com.badlogic.androidgames.framework.impl.GLGraphics;
import
com.badlogic.androidgames.framework.math.Vector2;
public class
Camera2D {
public final
Vector2 position;
public float
zoom;
public final float
frustumWidth;
public final float
frustumHeight;
final
GLGraphics glGraphics;
As discussed, we store the camera's position, frustum width and height, and zoom factor as
members. The position and zoom factor are public, so we can easily manipulate them. We also
need a reference to
GLGraphics
so that we can get the up-to-date width and height of the screen
in pixels for transforming touch coordinates to world coordinates.
public
Camera2D(GLGraphics glGraphics,
float
frustumWidth,
float
frustumHeight) {
this
.glGraphics = glGraphics;
this
.frustumWidth = frustumWidth;
this
.frustumHeight = frustumHeight;
this
.position =
new
Vector2(frustumWidth / 2, frustumHeight / 2);
this
.zoom = 1.0f;
}
In the constructor, we take a
GLGraphics
instance, and the frustum's width and height at the
zoom factor 1, as parameters. We store them and initialize the position of the camera to look
at the center of the box bounded by (0,0,1) and (
frustumWidth
,
frustumHeight
,-1), as shown in
Figure
8-19
. The initial zoom factor is set to 1.
public void
setViewportAndMatrices() {
GL10 gl = glGraphics.getGL();
gl.glViewport(0, 0, glGraphics.getWidth(), glGraphics.getHeight());
gl.glMatrixMode(GL10.
GL_PROJECTION
);
gl.glLoadIdentity();
gl.glOrthof(position.x - frustumWidth * zoom / 2,
position.x + frustumWidth * zoom / 2,
position.y - frustumHeight * zoom / 2,
position.y + frustumHeight * zoom / 2,
1, -1);
gl.glMatrixMode(GL10.
GL_MODELVIEW
);
gl.glLoadIdentity();
}
The
setViewportAndMatrices()
method sets the viewport to span the whole screen, and sets
the projection matrix in accordance with your camera's parameters, as discussed previously.
At the end of the method, we tell OpenGL ES that all further matrix operations are targeting the