我编写了左右移动玩家的代码,当玩家向左移动时,它有一个动画,当他向右移动时,它有另一个动画。
这是代码(dt 是 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);
}
所以我也想用加速度计移动玩家(在移动设备上)。我做到了,但现在我不知道如何检查玩家是否向左或向右移动以给他不同的动画
我的代码:
// 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);
最佳答案
这取决于您的游戏的方向。
position.x -= Gdx.input.getAccelerometerX() * speed * dt;
此实现看起来不错,因为 getAccelerometerX 值返回 [-10,10] 中的值。
但是,如果您的手机放在 table 上,那么该值将不会正好为 0。 假设您想要在加速度 >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);
}
关于java - LibGDX 加速度计 - Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24294503/