eye-therapy-2 / Assets / Scripts / UI / VRModeSwitch.cs
VRModeSwitch.cs
Raw
using System.Collections;
using UnityEngine;

public class VRModeSwitch : MonoBehaviour, IListener
{
    [SerializeField] private RectTransform button = null;
    [SerializeField] private RectTransform positionOff = null;
    [SerializeField] private RectTransform positionOn = null;

    public bool IsOn { get; private set; } = false;
    private float travelTime = 0.1f;

    void Start()
    {
        IsOn = PlayerPrefs.GetInt("VRControlMode", 1) > 0;
        //Debug.Log(PlayerPrefs.GetInt("VRControlMode", 1));
        if (IsOn) button.position = positionOn.position;
        EventManager.Instance.AddListener(EVENT_TYPE.ON_VR_CONTROLMODE_SWITCHED, this);
    }

    public void OnEvent<T>(EVENT_TYPE eventType, Component Sender, T param = default)
    {
        switch(eventType)
        {
            case EVENT_TYPE.ON_VR_CONTROLMODE_SWITCHED:
                if (Sender != this) Switch();
                break;
        }
    }

    public void SwitchButton()
    {
        Switch();
        if (IsOn) EventManager.Instance.PostNotification(EVENT_TYPE.ON_VR_CONTROLMODE_SWITCHED, this, 1);
        else EventManager.Instance.PostNotification(EVENT_TYPE.ON_VR_CONTROLMODE_SWITCHED, this, 0);
    }

    private void Switch()
    {
        StopAllCoroutines();
        IsOn = !IsOn;
        if (IsOn) StartCoroutine(ChangeButtonPosition(positionOn.position));
        else StartCoroutine(ChangeButtonPosition(positionOff.position));
    }

    private IEnumerator ChangeButtonPosition(Vector3 targetPosition)
    {
        Vector3 startPosition = button.position;
        float t = 0f;
        while(t < travelTime)
        {
            button.position = Vector3.Lerp(startPosition, targetPosition, t / travelTime);
            t += Time.deltaTime;
            yield return null;
        }
        button.position = targetPosition;
    }
}