I'm making a LibGDX game using Android Studio where an alien UFO has to avoid incoming asteroids, and the UFO moves using accelerometer data.
//Gets and smoothens accelerometer data. Values for x and y are switched because the game is played in landscape mode.
currentAccelerometerX = Gdx.input.getAccelerometerY();
currentAccelerometerX = currentAccelerometerX * alpha + lastAccelerometerX * (1 - alpha);
currentAccelerometerY = Gdx.input.getAccelerometerX();
currentAccelerometerY = currentAccelerometerY * alpha + lastAccelerometerY * (1 - alpha);
//Moves the alien
alien.alienX += (currentAccelerometerX * 5);
alien.alienY -= (currentAccelerometerY * 5);
lastAccelerometerY = currentAccelerometerY;
lastAccelerometerX = currentAccelerometerX;
This code works when the phone is being held so that the back of the phone is parallel to the floor, but such a position can get uncomfortable to play in after a while. I was wondering how I could take into account the current rotation of the device and adjust the movement of the UFO accordingly.
The problem only seems to be with the Y position of the alien, meaning the x accelerometer data of the phone(the values are switched since the game is played in landscape mode). When the phone is held at an angle to the floor, then the UFO just stays near the bottom edge of the screen.
JollyGoodSir, when a new game starts, take a snapshot of the current state of the accelerometer and set that as your base point. Now when you check the state of the accelerometer for changes to see how the tilt is being changed, compare it as a delta to this base value. Now your game will simply calibrate to whatever position you held the device in when the game started. Happy days :-)