Game Development Reference
In-Depth Information
Touching the screen eats
the CPU
: Even if we sleep in our
onTouch()
method,
the system has to process the events in the kernel as reported by the driver.
On old devices, such as the Hero or G1, this can use up to 50 percent of the
CPU, which leaves a lot less processing power for our main loop thread. As a
consequence, our perfectly fine frame rate will drop considerably, sometimes to
the point where the game becomes unplayable. On second-generation devices,
the problem is a lot less pronounced and can usually be ignored. Sadly, there's
no solution for this on older devices.
Processing Multitouch Events
Warning: Major pain ahead! The multitouch API has been tagged onto the
MotionEvent
class,
which originally handled only single touches. This makes for some major confusion when trying
to decode multitouch events. Let's try to make some sense of it.
Note
The multitouch API apparently is also confusing for the Android engineers that created it. It
received a major overhaul in SDK version 8 (Android 2.2) with new methods, new constants, and
even renamed constants. These changes should make working with multitouch a little bit easier.
However, they are only available from SDK version 8 onward. To support all multitouch-capable
Android versions (2.0+), we have to use the API of SDK version 5.
Handling multitouch events is very similar to handling single-touch events. We still implement
the same
OnTouchListener
interface we implemented for single-touch events. We also get
a
MotionEvent
instance from which to read the data. We also process the event types we
processed before, like
MotionEvent.ACTION_UP
, plus a couple of new ones that aren't too
big of a deal.
Pointer IDs and Indices
The differences between handling multitouch events and handling single-touch events
start when we want to access the coordinates of a touch event.
MotionEvent.getX()
and
MotionEvent.getY()
return the coordinates of a single finger on the screen. When we process
multitouch events, we use overloaded variants of these methods that take a
pointer index
. This
might look as follows:
event.getX(pointerIndex);
event.getY(pointerIndex);
Now, one would expect that
pointerIndex
directly corresponds to one of the fingers touching
the screen (for example, the first finger that touched has
pointerIndex
0, the next finger that
touched has
pointerIndex
1, and so forth). Unfortunately, this is not the case.
The
pointerIndex
is an index into internal arrays of the
MotionEvent
that holds the coordinates
of the event for a specific finger that is touching the screen. The real identifier of a finger on the
screen is called the
pointer identifier
. A pointer identifier is an arbitrary number that uniquely
identifies one instance of a pointer touching the screen. There's a separate method called