- Home /
UNITY 3D - Set the start positon of the gyroscope to initial phone position
Hello everybody,
I am making a mobile VR project in unity and I have a 360-video that starts playing where I can look around using a VR headset.
I am trying to set the start rotation of the video to the same rotation as my phones. So no matter where I look when I start the video, that should be my start rotation. I used Input.gyro.attitude in the start but that did not fix my problem. I think I am using it wrong.
I tried to find a solution to this and nowhere on the internet I could found a solution to this problem I encounter. I appreciate any help!
This is my code(on the camera inside the sphere): using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI;
public class Gyroscope : MonoBehaviour
{
private bool gyroEnabled;
private Gyroscope gyro;
private GameObject cameraContainer; //A camera container for my main camera
private GameObject videoSphere; //The sphere my video is in
private Quaternion rot;
private void Start()
{
videoSphere = GameObject.FindGameObjectWithTag("Video");
cameraContainer = new GameObject("Camera Container");
gyroEnabled = EnableGyro();
cameraContainer.transform.position = transform.position; //put the cameracontainer into the sphere
cameraContainer.transform.rotation = Input.gyro.attitude; //here I want to set the cameracontainer to the rotation of my phones gyroscope
transform.SetParent(cameraContainer.transform); //make my main camera a child of the camera Container
videoSphere.transform.localRotation = cameraContainer.transform.rotation; //Here I wanted to set my sphere rotation to the camera rotation
Debug.Log(videoSphere.transform.localRotation);
}
private bool EnableGyro()
{
if (SystemInfo.supportsGyroscope)
{
Input.gyro.enabled = true; //turn on my gyroscope
cameraContainer.transform.rotation = new Quaternion(0, 90, -90, 0); //rotate my camera container so the video shows good
rot = new Quaternion(0, 0, 1, 0); //set the variable rot so that you can turn your device
return true;
}
return false;
}
private void Update()
{
if (gyroEnabled)
{
transform.localRotation = Input.gyro.attitude * rot; //this makes you turn the device and it recognizes the input of the phones gyroscope
}
}
}
Answer by YetAnotherKen · Sep 09, 2019 at 07:48 PM
move as much of the setup of variables into the Awake method as you can. Then, anything relying on a object being created might not find the object until later in the frame like in Update, or even LateUpdate. Make sure you do some kind of check for existance of the object instance you are trying to use, like this:
if (cameraContainer != null)