Game Development Reference
In-Depth Information
Figure 8-22. Zooming, by manipulating the frustum size
To make our life complete, we should add one more thing. Imagine that we touch the screen and
want to figure out which point in our 2D world we touched. We already did this a couple of times
in our iteratively improving cannon examples. With a view frustum configuration that does not
factor in the camera's position and zoom, as seen in Figure 8-19 , we had the following equations
(see the update() method of our cannon examples):
worldX = (touchX / Graphics.getWidth()) × FRUSTUM_WIDTH;
worldY = (1 - touchY / Graphics.getHeight()) × FRUSTUM_HEIGHT;
First, we normalize the touch x and y coordinates to the range 0 to 1 by dividing by the screen's
width and height, and then we scale them so that they are expressed in terms of our world
space by multiplying them with the frustum's width and height. All we need to do is factor in the
position of the view frustum, as well as the zoom factor. Here's how we do that:
worldX = (touchX / Graphics.getWidth()) × FRUSTUM_WIDTH + x - FRUSTUM_WIDTH / 2;
worldY = (1 - touchY / Graphics.getHeight()) × FRUSTUM_HEIGHT + y - FRUSTUM_HEIGHT / 2;
Here, x and y are our camera's position in world space.
The Camera2D Class
Let's put all this together into a single class. We want it to store the camera's position, the
standard frustum width and height, and the zoom factor. We also want a convenient method that
sets the viewport (always use the whole screen) and projection matrix correctly. Additionally, we
want a method that can translate touch coordinates to world coordinates. Listing 8 - 15 shows
our new Camera2D class, with some comments.
 
Search WWH ::




Custom Search