I am creating a tool using Box2D and wanted to see if there was a way to match the direction of the real force of gravity acting on a mobile device.
I've got this completely working on iPad by binding to the devicemotion event. I check to see if the window's width is greater than its height in order to determine if the user is holding the device in landscape or portrait mode and I translate the data that the accelerometer provides based on that fact. For instance, if the iPad is being held with the home button to the bottom of the device, y is negative and corresponds to the force of gravity, as you might expect. If the device is rotated 90 degrees left or right, y moves toward 0 and x either increases to 9.8 or decreases to -9.8.
The problem is that when I move to an Android device whose orientation is landscape by default (i.e. the device's hardware is arranged in such a way that it is clear it is intended to be used mainly in landscape orientation) the x and y coordinates are reversed and the fact that the window's height is greater than its width can't be used to determine whether the user is holding the device with it's top "up" and its bottom "down".
Is there a more universal way for me to determine the direction that a device is being held and as a result know how I should interpret the accelerometer data so that my gravity is always relative to the Earth?
Here is a quick snippet of the method I'm using to determine the property values.
window.addEventListener('devicemotion', function(e) {
console.log(e.accelerationIncludingGravity.x);
console.log(e.accelerationIncludingGravity.y);
})