Android 加速度计在不同设备上的作用不同

Android Accelerometer acting different on different device

所以我目前正在开发一款游戏,如果您向左倾斜设备,屏幕上的对象会向左移动,如果您向右倾斜设备,屏幕上的对象会向右移动。

这在我拥有的所有设备(三星 Galaxy S5、三星 Galaxy 3 平板电脑和 ZTE Straight Talk phone)上都运行良好。但我已经发布了测试版和我的一个朋友那有一个平板电脑;三星 Galaxy 2 10 英寸。在上面,左右移动不起作用,但他必须上下倾斜它才能左右移动。看起来传感器几乎是旋转的。但是游戏被锁定在 "portrait" 位置。是否有可能在某些设备上传感器可能会旋转或以 "up" 向量和 "left" 向量被更改的方式实现?

我遇到了同样的问题,您需要在设置该对象的重力之前获取设备默认方向。

public int getDeviceDefaultOrientation() {

        WindowManager windowManager =  (WindowManager) getSystemService(WINDOW_SERVICE);

        Configuration config = getResources().getConfiguration();

        int rotation = windowManager.getDefaultDisplay().getRotation();

        if ( ((rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_180) &&
                config.orientation == Configuration.ORIENTATION_LANDSCAPE)
            || ((rotation == Surface.ROTATION_90 || rotation == Surface.ROTATION_270) &&    
                config.orientation == Configuration.ORIENTATION_PORTRAIT)) {
          return Configuration.ORIENTATION_LANDSCAPE;
        } else { 
          return Configuration.ORIENTATION_PORTRAIT;
        }
    }

例如,在我的例子中,我使用了 box2d,代码是这样的

if (box2dUtils.getWorld() != null) {
                    int orient=getDeviceDefaultOrientation();
                    if(orient==1){
                        box2dUtils.getWorld().setGravity(new Vec2(xaccel,yaccel));
                    }
                    else if(orient==2){

                        box2dUtils.getWorld().setGravity(new Vec2(-yaccel,-xaccel));
                    }// initially Vec2(xaccel, yaccel);
                    else{
                        box2dUtils.getWorld().setGravity(new Vec2(xaccel,yaccel));

                    }
                }