Using accelerometer we get the input from our devices, as we are getting like touching the screen, keyboard, mouse etc.

Accelerometer

An accelerometer is a device which measures the acceleration of a device on three axes, this will work on at least Android. By using this acceleration we can move our actor in our gaming environment.

The axes in an Android device are setup as follows:

 

For phones, portrait mode (as in the image above) is considered as the default orientation. For tablets, landscape mode is considered as the default orientation. A default landscape orientation device has it”s axes rotated, so that the y-axis points up the smaller side of the device and the x-axis points to the right of the wider side.

 

Using the accelerometer

We can check if an accelerometer is present with the following call :

Gdx.input.isPeripheralAvailable( Peripheral.Accelerometer )

If accelerometer is present in your device then it return true else false.

Do”nt forget to declare the accelerometer requirement on the AndroidManifest.xml.

<uses-feature

android:name=”android.hardware.sensor.accelerometer”

android:required=”true” />

 

And the following calls retrieve the accelerometer”s current data:

 

Gdx.input.getAccelerometerX();// points to the right (when in portrait orientation)

Gdx.input.getAccelerometerY();// points upwards (when in portrait orientation)

Gdx.input.getAccelerometerZ();// points to the front of the display (coming out of the screen)

 

Each value that is retrieved from the device ranges from -10 to 10. Devices that don”t have accelerometer support will return zero.

 

If the game is in portrait mode, our game”s x-axis corresponds to the accelerator”s x-axis.

Actor.position.x = Gdx.input.getAccelerometerX()*MAX_HORIZONTAL_SPEED * delta;

But if the game is in landscape mode, our game”s x-axis corresponds to the accelerator”s y-axis

Actor.position.x = Gdx.input.getAccelerometerY()*MAX_HORIZONTAL_SPEED * delta;

 You can check the effect of Accelerometer (bucket movement) in the below app:

I hope you will enjoy with accelerometer in your libgdx gaming environment.

 

-By

Arvind kaushal

Android Developer