Search code examples
c#visual-studiounity-game-enginegyroscope

Unity gyroscope reads only two axes


I want to make it so that the gyroscope will only change the x and y-axes of an object. There is code for one axis and for three axes (mostly used), but I couldn't find anything about two axis and wasn't able to do it myself.


Solution

  • Reset the z-axis or whatever axis before applying-

    private Vector3 startEulerAngles;
    private Vector3 startGyroAttitudeToEuler;
    
    private void Start()
    {
        Input.gyro.enabled = true;
        startEulerAngles = transform.eulerAngles;
        startGyroAttitudeToEuler = Input.gyro.attitude.eulerAngles;
    }
    
    private void Update()
    {
        Vector3 deltaEulerAngles = Input.gyro.attitude.eulerAngles - startGyroAttitudeToEuler;
    
        // Z-axis reset, so it won't be applied. 
        deltaEulerAngles.z = 0.0f;
    
        transform.eulerAngles = startEulerAngles - deltaEulerAngles;
    }