Game Development Reference
In-Depth Information
@Override
public void
onAccuracyChanged(Sensor sensor,
int
accuracy) {
// nothing to do here
}
@Override
public void
onSensorChanged(SensorEvent event) {
yaw=event.values[0];
pitch=event.values[1];
roll=event.values[2];
}
public float
getYaw() {
return
yaw;
}
public float
getPitch() {
return
pitch;
}
public float
getRoll() {
return
roll;
}
}
We won't use the compass in any of the games in this topic, but if you are going to reuse the
framework we develop, this class might come in handy.
The Pool Class: Because Reuse Is Good for You!
What's the worst thing that can happen to us as Android developers? World-stopping
garbage collection! If you look at the
Input
interface definition in Chapter 3, you'll find the
getTouchEvents()
and
getKeyEvents()
methods. These methods return
TouchEvent
and
KeyEvent
lists. In our keyboard and touch event handlers, we constantly create instances of
these two classes and store them in lists that are internal to the handlers. The Android input
system fires many of these events when a key is pressed or a finger touches the screen, so we
constantly create new instances that are collected by the garbage collector in short intervals. In
order to avoid this, we implement a concept known as
instance pooling
. Instead of repeatedly
creating new instances of a class, we simply reuse previously created instances. The
Pool
class
is a convenient way to implement that behavior. Let's have a look at its code in Listing 5-7, which
is broken up again, containing appropriate commentary.
Listing 5-7. Pool.java; Playing Well with the Garbage Collector
package
com.badlogic.androidgames.framework;
import
java.util.ArrayList;
import
java.util.List;
public class
Pool<T> {