Allowing both landscape options and accelerometer

2019-08-12 16:43发布

I've completed the SimpleApp tutorial for libgdx. I have changed the controls for the game to use the accelerometer instead of touch input, in the following way:

  • In MainActivity.java

    cfg.useAccelerometer = true;
    
  • In DropGame.java

    float acc = Gdx.input.getAccelerometerY();
    bucket.x += acc * 120 * Gdx.graphics.getDeltaTime();
    

My question is, how do I allow both landscapes? I would like to be able to turn my device 180 degrees from one landscape orientation to the other, and have the game rotate with it.

The closest I've gotten to what I want, is setting android:screenOrientation="sensorLandscape" in the manifest, but while it does rotate the screen without allowing portrait mode, it also inverts the accelerometer controls.

I'm new to Android and libgdx, so I might have missed something obvious.

Thanks in advance!

2条回答
唯我独甜
2楼-- · 2019-08-12 17:07

Here's my solution, based on P.T.s answer:

float rot = Gdx.input.getRotation() - 180;
float acc = Gdx.input.getAccelerometerY();
bucket.x += acc * BUCKET_SPEED * Gdx.graphics.getDeltaTime() * (rot / Math.abs( rot ) * -1);

Now I can turn my device 180 degrees and the game will follow, and the accelerometer controls works the same way both ways.

查看更多
你好瞎i
3楼-- · 2019-08-12 17:20

From the Libgdx accelerometer wiki (specifically this section), the accelerometer data is always relative to portrait orientation.

You are expected to use the result of Gdx.input.getNativeOrientation() or Gdx.input.getRotation() and flip the results as necessary.

The wiki and the javadoc are a bit inconsistent with respect to "native" orientations, but it does look like the code does what the wiki says ("portait" is always the default orientation, even on tablets where Android defaults to landscape).

查看更多
登录 后发表回答