Game Development Reference
In-Depth Information
Why do we store the Vector2 instances as class members? We can instantiate them every time
we need them, but that would make the garbage collector angry. In general, we try to instantiate
all the Vector2 instances once and then reuse them as often as possible.
public CannonScreen(Game game) {
super (game);
glGraphics = ((GLGame) game).getGLGraphics();
vertices = new Vertices(glGraphics, 3, 0, false , false );
vertices.setVertices( new float [] { -0.5f, -0.5f,
0.5f, 0.0f,
-0.5f, 0.5f }, 0, 6);
}
In the constructor, we fetch the GLGraphics instance and create the triangle according to
Figure 8-4 .
@Override
public void update( float deltaTime) {
List<TouchEvent> touchEvents = game.getInput().getTouchEvents();
game.getInput().getKeyEvents();
int len = touchEvents.size();
for ( int i = 0; i < len; i++) {
TouchEvent event = touchEvents.get(i);
touchPos.x = (event.x / ( float ) glGraphics.getWidth())
* FRUSTUM_WIDTH;
touchPos.y = (1 - event.y / ( float ) glGraphics.getHeight())
* FRUSTUM_HEIGHT;
cannonAngle = touchPos.sub(cannonPos).angle();
}
}
Next up is the update() method. We simply loop over all TouchEvent is and calculate the angle for
the cannon. This can be done in a couple of steps. First, we transform the screen coordinates
of the touch event to the world coordinate system, as discussed earlier. We store the world
coordinates of the touch event in the touchPoint member. We then subtract the position of the
cannon from the touchPoint vector, which will result in the vector depicted in Figure 8-5 . We
then calculate the angle between this vector and the x axis. And that's all there is to it!
@Override
public void present( float deltaTime) {
GL10 gl = glGraphics.getGL();
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, FRUSTUM_WIDTH, 0, FRUSTUM_HEIGHT, 1, -1);
gl.glMatrixMode(GL10. GL_MODELVIEW );
gl.glLoadIdentity();
 
Search WWH ::




Custom Search