# How should I determine direction from a phone's orientation & accelerometer?

I have an Android application which moves a ball based on the orientation of the phone. I've been using the following code to extract the data - but how do I use it to determine what direction the ball should actually travel in?

public void onSensorChanged(int sensor, float[] values) {
// TODO Auto-generated method stub
synchronized (this) {
Log.d("HIIIII :- ", "onSensorChanged: " + sensor + ", x: " + values[0] + ", y: " + values[1] + ", z: " + values[2]);
if (sensor == SensorManager.SENSOR_ORIENTATION) {
System.out.println("Orientation X: " + values[0]);
System.out.println("Orientation Y: " + values[1]);
System.out.println("Orientation Z: " + values[2]);
}
if (sensor == SensorManager.SENSOR_ACCELEROMETER) {
System.out.println("Accel X: " + values[0]);
System.out.println("Accel Y: " + values[1]);
System.out.println("Accel Z: " + values[2]);
}
}
}

• I've heavily edited your question. Please check what I've written to make sure I interpreted your question correctly. – doppelgreener Apr 13 '12 at 13:34
• Yes, Thank you very much, But give me some suggestion for android Game Development. If possible, Thanks again to you.. – Manoj Kumar Apr 16 '12 at 4:34
• I don't have an answer to provide or else I probably would have already provided it. – doppelgreener Apr 16 '12 at 4:43

I'm not sure but I guess the simplest way to use those data is something like this:

public void onSensorChanged(int sensor, float[] values) {
// TODO Auto-generated method stub
synchronized (this) {
Log.d("HIIIII :- ", "onSensorChanged: " + sensor + ", x: " + values[0] + ", y: " + values[1] + ", z: " + values[2]);

if (sensor == SensorManager.SENSOR_ACCELEROMETER) {
ball.x += values[0];
ball.y += values[1];
}
}
}


note that accelerometer is a device which computes the acceleration vector applied to the device. gravity is simply applying some acceleration to the device. so the raw data itself can be used to determine direction of device. you make movements more stable you can use average value of past 10 ticks instead of just latest value. also you can multiply a rotation matrix to the values so that user doesn't need to keep device exactly parallel to the ground.