IPhone OpenGL screen orientation using the accelerometer
Even tough it’s not mandatory to support all screen orientations it’s always nice to support at least 2 of them.
Let’s imagine your game is landscaped, by some reason the user may want to use either with the home button on the left or on the right. Most games support this, if you flip the device, the game will too.
I’ve been using OpenGL to support the device orientation, most people on forums want an automatic solution, but belive me, it’s best that you have control on this.
So for Landscape with Home button on the right
It’s something like:
So basically we are drawing all in a regular direction but rotating everything 90 degrees and translating to fit the screen properly.
For the home button on the left
These are the tricky ones, you can figure out the Portrait Upside down =)
Although you could use iOS api to auto rotate this automatically I’ve read on numerous places that it’s slows down everything a bit and doing this on OpenGL is pretty quick and clean and if you ever port your game to another device (Android, etc) you don’t have to care about this again.
So now for the tricky part, to detect the device current orientation, the accelerometer can help out pretty good. We can check for the current angle to calculate where the device is pointing.
So what you should do is keep a variable that stores the current Orientation so when you draw you know exactly what rotation to apply to the matrix.
I’ve tested this code on a real device with pretty good results. Also it won’t slow down everything and if you think it does just check screen orientation at greater intervals.
Some cool things you can do it when switching to iterate the rotation angle, that way you can simulate the screen rotation same way iOS does. Also you may want to put some sort of delay when switching.
Here’s the result