Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The problem here is that some devices are portrait mode by default, and some are landscape by default. The y axis of the accelerometer is aligned to the "up" direction of the device in its natural state, which changes from device to device. On a regular portrait-by-default phone, the y axis is aligned to the longest side of the screen:</p> <pre><code> +------+ | | ^ | | y| | | | | | | | | +----&gt; | | x +------+ </code></pre> <p>But on a tablet, or a wide phone that is landscape by default, the y axis is aligned to the shortest side of the screen.</p> <pre><code> +--------------+ | | ^ | | y| | | | +--------------+ +-------&gt; x </code></pre> <p>The solution is to check <a href="http://developer.android.com/reference/android/view/Display.html#getRotation%28%29" rel="nofollow">android.view.Display.getRotation()</a>. On a portrait device that is in its default orientation (i.e. like the fist ASCII art diagram) this will return <code>ROTATION_0</code>. On a landscape device turned so it is with the longest part of the screen pointing up it will return <code>ROTATION_90</code> (or <code>ROTATION_270</code>).</p> <p>Similarly, if you force your game to be in landscape mode with <code>android:screenOrientation="landscape"</code> in the AndroidManifest.xml or via <code>ScreenOrientation.LANDSCAPE</code> as in your snippet, then a portrait phone will return <code>ROTATION_90</code> and a landscape device <code>ROTATION_0</code>.</p> <p>In the case of a forced landscape game you would need something like this:</p> <pre><code>WindowManager wm = (WindowManager) context.getSystemService( Context.WINDOW_SERVICE); boolean portrait = wm.getDefaultDisplay().getRotation() == Surface.ROTATION_90; // ... float dy; if (portrait) { dy = pAccelerometerData.getX(); } else { dy = pAccelerometerData.getY(); } if (dy &lt; -1) { // move ball up } else if (dy &gt; 1) { // move ball down } </code></pre> <p>This is only for Android 2.2 and later. Earlier devices were all portrait, and the <code>getRotation()</code> method does not exist, so you'll have to use reflection or similar techniques if you want to support devices that haven't got Froyo.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload