Game Development Reference
In-Depth Information
We can also simplify the update() method of the test. Since we added the Camera2D.
touchToWorld() method to the Camera2D class, we might as well use it. We can replace this
snippet from the update() method:
touchPos.x = (event.x / (float) glGraphics.getWidth()) * WORLD_WIDTH;
touchPos.y = (1 - event.y / (float) glGraphics.getHeight()) * WORLD_HEIGHT;
with this:
camera.touchToWorld(touchPos.set(event.x, event.y));
Neat—now everything is nicely encapsulated. But it would be very boring if we didn't use the
features of your Camera2D class to their full extent. Here's the plan: we want to have the camera
look at the world in the “normal� way as long as the cannonball does not fly. That's easy; we're
already doing that. We can determine whether the cannonball flies or not by checking whether
the y coordinate of its position is less than or equal to zero. Since we always apply gravity to the
cannonball, it will fall even if we don't shoot it, so that's a cheap way to check matters.
Our new addition will come into effect when the cannonball is flying (when the y coordinate is
greater than zero). We want the camera to follow the cannonball. We can achieve this by simply
setting the camera's position to the cannonball's position. That will always keep the cannonball
in the center of the screen. We also want to try out our zooming functionality. Therefore, we can
increase the zoom factor depending on the y coordinate of the cannonball: the further away from
zero, the higher the zoom factor. If the cannonball has a higher y coordinate, this will make the
camera zoom out. Here's what we need to add at the end of the update() method in our test's
screen:
if(ball.position.y > 0) {
camera.position.set(ball.position);
camera.zoom = 1 + ball.position.y / WORLD_HEIGHT;
} else {
camera.position.set(WORLD_WIDTH / 2, WORLD_HEIGHT / 2);
camera.zoom = 1;
}
As long as the y coordinate of our ball is greater than zero, the camera will follow it and zoom
out. Just add a value to the standard zoom factor of 1. That value is just the relation between
the ball's y position and the world's height. If the ball's y coordinate is at WORLD_HEIGHT , the zoom
factor will be 2, so we'll see more of our world. The way this is done can be really arbitrary; we
can come up with any formula that we want here—there's nothing magical about it. In case
the ball's position is less than or equal to zero, we show the world normally, as we did in the
previous examples.
Texture Atlas: Because Sharing Is Caring
Up until this point, we have used only a single texture in our programs. What if we want to
render not only Bob, but other superheroes, enemies, explosions, or coins as well? We could
have multiple textures, each holding the image of one object type. But OpenGL ES wouldn't like
that too much, since we'd need to switch textures for every object type we render (that is, bind
 
Search WWH ::




Custom Search