I write code for moving player left and right, also when player moves left it has one animation, and when he moves right he has another animation.
This is the code (dt is deltaTime):
// Moving player desktop
if (Gdx.input.isKeyPressed(Keys.A)) // Left
{
position.x -= speed * dt;
currentFrame = animation.getKeyFrame(4 + (int) stateTime);
}
else if (Gdx.input.isKeyPressed(Keys.D)) // Right
{
position.x += speed * dt;
currentFrame = animation.getKeyFrame(8 + (int) stateTime);
}
else // Normal
{
currentFrame = animation.getKeyFrame(12);
}
So I also want to move player (on mobile devices) with accelerometer. I done that, but now I don't know how to check if player is moving left or right to give him different animations
My code:
// Moving player android
// position.x -= Gdx.input.getAccelerometerX() * speed * dt;
if( PLAYER MOVING LEFT)
{
// Player moving left....
currentFrame = animation.getKeyFrame(4 + (int) stateTime);
}
else if (PLAYER MOVING RIGHT)
{
// Player moving right....
currentFrame = animation.getKeyFrame(8 + (int) stateTime);
}
else
currentFrame = animation.getKeyFrame(12);
It depends of the orientation if your game.
position.x -= Gdx.input.getAccelerometerX() * speed * dt;
This implementation looks good, because the getAccelerometerX value returns a value from [-10,10].
But, if your phone is on a table let's say, that value won't be exactly 0. Let's say that you want to move your player when the acceleration is >0.3f.
float acceleration=Gdx.input.getAccelerometerX(); // you can change it later to Y or Z, depending of the axis you want.
if (Math.abs(acceleration) > 0.3f) // the accelerometer value is < -0.3 and > 0.3 , this means that is not really stable and the position should move
{
position.x -= acceleration * speed * dt; // we move it
// now check for the animations
if (acceleration < 0) // if the acceleration is negative
currentFrame = animation.getKeyFrame(4 + (int) stateTime);
else
currentFrame = animation.getKeyFrame(8 + (int) stateTime);
// this might be exactly backwards, you'll check for it
} else {
// the sensor has some small movements, probably the device is not moving so we want to put the idle animation
currentFrame = animation.getKeyFrame(12);
}