Loading...

Adding simple Gyro Support to Unity3D

As I do a lot of VR / 360 Content production I thought it would be a good idea to learn the basics of Gyroscope Support in Android.
To gain some insight into how to code for Android Gyro Support I came across this tutorial.

To the Right I have included the working code to allow the camera to move via Gyro inputs.
I started with a basic scene and simply attached the camera to this script.


Gyro Test 01

REQUIREMENTS: Mobile Device, Gyroscope, WebGL
Unfortunately WebGL is not supported on Samsung S7, If your mobile does support it this demo may work. The best method is to install the APK via the link below.

Download:
APK : GyroTest01.apk
Unity Project: Unity Project

References:
Blog Cover image – https://techinfomobi.blogspot.com.au/2017/02/sensors-2.html
Content –¬†https://youtu.be/P5JxTfCAOXo

C# Source Code

Built in Visual Basic 2017

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GyroControl : MonoBehaviour {

	private bool gyroEnabled;
	private Gyroscope gyro;

	private GameObject cameraContainer;
	private Quaternion rot;

	private void Start ()
	{
		cameraContainer = new GameObject("Camera Container");
		cameraContainer.transform.position = transform.position;
		transform.SetParent (cameraContainer.transform);

		gyroEnabled = EnableGyro ();
	}

	private bool EnableGyro()
	{
		if (SystemInfo.supportsGyroscope)
        {
			gyro = Input.gyro;
			gyro.enabled = true;

            cameraContainer.transform.rotation = Quaternion.Euler(90f, 90f, 0f);
            rot = new Quaternion(0, 0, 1, 0);

			return true;
		}
		return false;

	}

    private void Update()
    {
        if (gyroEnabled)
        {
            transform.localRotation = gyro.attitude * rot;
        }
    }

}