## The Implementation

So let's summarize all this by forming a simple plan of attack:

■ We design all our graphic assets for a fixed target resolution (320! 480 in Mr. Nom's case).

■ We create a Bitmap the same size as our target resolution and direct all our drawing calls to it, effectively working in a fixed-coordinate system.

■ When we are done drawing a frame of our game, we draw our framebuffer Bitmap stretched to the SurfaceView. On devices with a lower screen resolution the image will be scaled down, and on devices with a higher resolution it will be scaled up.

■ We have to make sure that all the UI elements the user interacts with are big enough at all screen densities when we do our scaling trick. This is something we can do in the graphic asset-design phase using the sizes of actual devices in combination with the formulas shown previously.

Now that we know how we will handle different screen resolutions and densities, I can also explain the scaleX and scaleY variables we met when we implemented the SingleTouchHandler and MultiTouchHandler a few pages earlier.

All our game code will be tuned to work with our fixed target resolution (320! 480 pixels). If we receive touch events on a device that has a higher or lower resolution, the x- and y-coordinates of those events will be defined in the View's coordinate system, not in our target resolution coordinate system. Thus we have to transform the coordinates from their original system to our system based on the scaling factors. Here's how we do that:

transformed touch x = real touch x * (target pixels on x axis / real pixels on x axis) transformed touch y = real touch y * (target pixels on y axis / real pixels on y axis)

Let's calculate a simple example for a target resolution of 320! 480 pixels and a device with a resolution of 480! 800 pixels. If we touch the middle of the screen, we'll receive an event with the coordinates (240,400). Using the two preceding formulas, we arrive at the following, which is exactly in the middle of our target coordinate system:

transformed touch x = 240 * (320 / 480) = 160 transformed touch y = 400 * (480 / 800) = 240

Let's do another one, assuming a real resolution of 240! 320, again touching the middle of the screen, at (120,160):

transformed touch x = 120 * (320 / 240) = 160 transformed touch y = 160 * (480 / 320) = 240

Hurray, it works in both directions. If we multiply the real touch event coordinates by the target factor divided by the real factor, we don't have to care about all this transforming in our actual game code. All the touch coordinates will be expressed in our fixed-target coordinate system.

With that out of our way, let's implement the last few classes of our game framework.

0 0