﻿
using UnityEngine;

/**
 * 陀螺仪控制
 */
namespace VRPlayerSDK.sample
{
    public class GyroController : MonoBehaviour
    {
        public bool ifTouch = true;


        // Optional, allows user to drag left/right to rotate the world.
        private const float DRAG_RATE = .2f;
        float dragYawDegrees = 0f;


        void Start()
        {
            // Make sure orientation sensor is enabled.
            Input.gyro.enabled = true;
        }

        public string GetGyrpInfo()
        {
            Quaternion gyroRotation = Quaternion.Euler(90f, 0f, 0f) * Input.gyro.attitude * Quaternion.Euler(0f, 0f, 180f);
            return "dragYawDegrees:" + dragYawDegrees + ",Gyro:" + gyroRotation.eulerAngles.ToString() + ",transform:" + transform.localRotation.eulerAngles.ToString();
        }


        void Update()
        {
#if !UNITY_EDITOR
        // android-developers.blogspot.com/2010/09/one-screen-turn-deserves-another.html
        // developer.android.com/guide/topics/sensors/sensors_overview.html#sensors-coords
        //
        //     y                                       x
        //     |  Gyro upright phone                   |  Gyro landscape left phone
        //     |                                       |
        //     |______ x                      y  ______|
        //     /                                       \
        //    /                                         \
        //   z                                           z
        //
        //
        //     y
        //     |  z   Unity
        //     | /
        //     |/_____ x
        //

        // Update `dragYawDegrees` based on user touch.
        if (ifTouch) {
            CheckDrag();
        }


        transform.localRotation =
          // Allow user to drag left/right to adjust direction they're facing.
          Quaternion.Euler(0f, -dragYawDegrees, 0f) *

          // Neutral position is phone held upright, not flat on a table.
          Quaternion.Euler(90f, 0f, 0f) *

          // Sensor reading, assuming default `Input.compensateSensors == true`.
          Input.gyro.attitude *

          // So image is not upside down.
          Quaternion.Euler(0f, 0f, 180f);

#endif
        }

        /**
         * 处理单摄像头的角度拖拽
         */
        void CheckDrag()
        {
            if (Input.touchCount != 1)
            {
                return;
            }

            Touch touch = Input.GetTouch(0);
            if (touch.phase != TouchPhase.Moved)
            {
                return;
            }

            dragYawDegrees += touch.deltaPosition.x * DRAG_RATE;
        }
    }
}
