Game Development Reference
In-Depth Information
tablets, for example. So how does one cope with this? Use this handy-dandy code snippet and
you should be good to go:
int screenRotation;
public void onResume() {
WindowManager windowMgr =
(WindowManager)activity.getSystemService(Activity.WINDOW_SERVICE);
// getOrientation() is deprecated in Android 8 but is the same as getRotation(),
which is the rotation from the natural orientation of the device
screenRotation = windowMgr.getDefaultDisplay().getOrientation();
}
static final int ACCELEROMETER_AXIS_SWAP[][] = {
{1, -1, 0, 1}, // ROTATION_0
{-1, -1, 1, 0}, // ROTATION_90
{-1, 1, 0, 1}, // ROTATION_180
{1, 1, 1, 0}}; // ROTATION_270
public void onSensorChanged(SensorEvent event) {
final int [] as = ACCELEROMETER_AXIS_SWAP [screenRotation];
float screenX = ( float )as[0] * event.values[as[2]];
float screenY = ( float )as[1] * event.values[as[3]];
float screenZ = event.values[2];
// use screenX, screenY, and screenZ as your accelerometer values now!
}
Here are a few closing comments on accelerometers:
ï?®
As you can see in the screenshot on the right in Figure
4-9 , the
accelerometer values might sometimes go over their specified range. This is
due to small inaccuracies in the sensor, so you have to adjust for that if you
need those values to be as exact as possible.
ï?®
The accelerometer axes always get reported in the same order, no matter
the orientation of your activity.
ï?®
It is the responsibility of the application developer to rotate the
accelerometer values based on the natural orientation of the device.
Reading the Compass State
Reading sensors other than the accelerometer, such as the compass, is very similar. In fact, it is so
similar that you can simply replace all instances of Sensor. TYPE_ACCELEROMETER in Listing 4-6
with Sensor. TYPE _ ORIENTATION and rerun the test to use our accelerometer test code as a
compass test!
You will now see that your x , y , and z values are doing something very different. If you hold the
device flat with the screen up and parallel to the ground, x will read the number of degrees for a
compass heading and y and z should be near 0. Now tilt the device around and see how those
numbers change. The x should still be the primary heading (azimuth), but y and z should show
you the pitch and roll of the device, respectively. Because the constant for TYPE_ORIENTATION
was deprecated, you can also receive the same compass data from a call to
SensorManager.getOrientation(float[] R, float[] values) , where R is a rotation matrix (see
SensorManager.getRotationMatrix() ) and values holds the three return values, this time in radians.
 
Search WWH ::




Custom Search