Unity gyroscope: Explained with code examples

Gyroscope is available in most of the latest mobile devices and can play a vital role as input for a game. In unity gyroscope is used mostly in racing, VR and AR games. Games with gyroscope can be more fun to play than the traditional input games. In this post we will cover how gyroscope can be used as input and how it can be implemented correctly to have a better player experience.

Difference between gyroscope and accelerometer

The main difference between gyroscope and accelerometer is that gyroscope can sense Orientation and accelerometer cannot. Though a tri-axis accelerometer can sense the orientation of a static object but when the object starts moving, the readings come out wrong.

Mainly gyroscope is used for measuring rotation and accelerometer for measuring linear motion. Let’s try to understand this with some examples. If you have a character in game. You want to move the character based on the device movement then you can use accelerometer. If you want the character to look around based on device rotation then you can use gyroscope.

Unity gyroscope input

Unity gyroscope input needs to be enabled before using. This is also a way to check if your device has an gyroscope.

  • Assign a object for gyro input using “Gyroscope object_name”. You can assign any name of your choice.
  • In the start function assign Gyroscope input by “object_name =Input.gyro”. You can also directly take the input if you don’t want to assign a variable,like the code below.
  • Enable gyroscope by typing “object_name.enabled=true”.
  • After enabling gyroscope you can take the device rotation by “Quanternion rot= Input.gyro.attitude”

Gyroscope input needs to be in taken into a Quanternion variable only. You can also directly assign it to a gameobject’s rotation.

Unity gyroscope camera

Let’s see how to make a camera rotate based on gyroscope input. We will break down a simple script to understand how you can do this.

using UnityEngine;
using System.Collections;
public class GyroRotate : MonoBehaviour {

void Start ()
Input.gyro.enabled = true;
void Update ()
player.transform.Rotate (0, -Input.gyro.rotationRateUnbiased.y, 0);

The start function in the code is used to enable gyro. This is mandatory for android devices. IOS has gyro enabled by default, so you can skip this line for ios devices. In the Update function we take the device rotation along the y axis and apply it to the game-object or camera in this case.

Gyroscope in device is right handed but in unity its left handed, that’s why the minus sign is added to the input. And yes this single line code is enough to make your first gyro based game. You make the development much fun using the Unity assets from the asset store.

Go ahead and test it out and leave your feedback on the comments below. You can learn more about unity scripting from our other post.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.