How to Write Gyroscope Controller with Unity3D

Gyroscope gives developers a wide range of exciting control variations. But when it comes to its integration and implementation of camera controller, lots of strange and magic things happen. Developers have to deal with different device orientations, initial camera positions and, of course, quaternions. I’m glad to share my experience and describe how we solved these problems at Heyworks. Hopefully, this will save efforts and nerves of those, who work with gyroscope for the first time.

In my example I want to demonstrate how to implement the following features in camera controller:

Device’s screen is supposed to work as a “window” into the virtual world so, that the turning the device around user could observe it.

It will support autorotation and work on every device orientation.

You will be able to detach the controller from camera, change its rotation and position from the code (play camera animation for example) and then attach controller back without noticeable hitches.

It will keep virtual world up axis in parallel with real world up axis and will recalibrate horizontal rotation.

The first problem we solve is different coordinate system reference types that are used in iOS devices and Unity3D: left-handed and right-handed. In order to convert quaternion from one system to another, let’s use the following function:

The controller should update camera rotation referenced to the base device rotation and reset base camera rotation in the horizontal plane. It means that if user starts the application pointing the device to the north, the game camera will not rotate to the virtual north. The camera will show the given direction. Below is the new function that takes into account camera base rotation and device base rotation.

I am prototyping with Razer Edge Pro Tablet (Win 8.1) and have tested this example as winRT (Windows Store) App. When I move the tablet around (pitch, yaw, roll), I get some movements, but it seems that Pitch/Yaw/Roll are all swapped/inverted somehow – definitely not like a “window to the 3d world”. Are you interested in helping me to get it work on windows?