1

我正在使用 Box2D 创建一个工具,并想看看是否有一种方法可以匹配作用在移动设备上的真实重力方向。

通过绑定到 devicemotion 事件,我已经完全在 iPad 上工作了。我检查窗口的宽度是否大于其高度,以确定用户是在横向还是纵向模式下握持设备,并根据该事实转换加速度计提供的数据。例如,如果 iPad 的 Home 键位于设备底部,则 y 为负值,对应于重力,正如您所料。如果设备向左或向右旋转 90 度,y 向 0 移动,x 要么增加到 9.8,要么减小到 -9.8。

问题是,当我移动到默认方向为横向的 Android 设备时(即,设备的硬件布置方式很明显,它主要用于横向),x 和 y 坐标是相反的并且窗口的高度大于其宽度的事实不能用于确定用户是否在顶部“向上”和底部“向下”的情况下握住设备。

是否有一种更通用的方法可以让我确定设备被握持的方向,从而知道我应该如何解释加速度计数据,以便我的重力始终相对于地球?

这是我用来确定属性值的方法的一个快速片段。

window.addEventListener('devicemotion', function(e) { console.log(e.accelerationIncludingGravity.x); console.log(e.accelerationIncludingGravity.y); })

4

1 回答 1

0

After working on this for the rest of the day, it looks like the answer is that you need to add a listener to the window for the orientationchange event (and also the resize event since some Android devices don't fire orientationchange) and then checking window.orientation, which is either 0, 180 or +/-90 based on orientation.

var orientation = window.orientation;

//Optionally add an evenr listener on resize here
window.addEventListener('devicemotion', function() {
    if(Math.abs(orientation) == 90) {
        //device is sideways
    } else {
        //device is vertical
    }
});

window.addEventListener('orientationchange', function(e) {
    if(PanScaleTool.scaleToolData.accelerometer == true) {

        if(Math.abs(e.beta) > 45) {
            orientation = window.orientation;
        } else {
            orientation = window.orientation;
        }
    }
});

In my limited testing with an iOS device and two android devices, 0 and 180 seem to always correspond to device is vertical (front facing camera at top of screen for example) or upside down. +/- 90 correspond to the other two orientations.

Here's another question on SO that I referenced for this answer

于 2014-04-10T20:42:45.833 回答