Reading Android Accelerometer in Any Direction

I am working on a game in Android, where the playerโ€™s movement (left, top, right, bottom) is calculated depending on the direction in which you tilt your device.

I also wanted to do this at the beginning of the game, it calculates the current slope, so if the player holds the phone in any position, he can still play the game.

Here is how I did it:

(at startup):

defaultAccelX = SceneManager.activity.getAccelX(); defaultAccelY = SceneManager.activity.getAccelY(); 

(and then with each update):

 float modifiedAccelX = (SceneManager.activity.getAccelX() - defaultAccelX); float modifiedAccelY = (SceneManager.activity.getAccelY() - defaultAccelY); 

Now it works if the player holds the phone at the bottom. But if I hold the phone upside down, the top and bottom change to the opposite, and the right does not work.

Does anyone know how I should work with him in any direction?

thanks

+4
source share
1 answer

In addition to linear acceleration sensors, Android provides access to orientation sensors.

 private SensorManager mSensorManager; private Sensor mSensor; ... mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION); 

An orientation sensor can give you azimuth (degree of rotation around the Z axis), pitch (the same, but the X axis) and a roll (the same, but along the Y axis).

The orientation sensor data can be obtained while your application is running, so even if the orientation of the phone is changed during playback, you can figure out which way up.

See: Android SDK: Position Sensors for more details.

0
source

Source: https://habr.com/ru/post/1492420/


All Articles