using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;

public class Compass : MonoBehaviour {
    RectTransform handle;
    public Transform cam;
    float randomRot = 0f;

    private void Start() {
        handle = this.GetComponent<RectTransform>();
        StartCoroutine(RandomRot());
    }



    IEnumerator RandomRot() {
        while (true) {
            var newRand = Random.Range(-5f, 5f);
            var wait = Random.Range(0.5f, 2f);

            var tween = DOTween.To(() => randomRot, x => randomRot = x, newRand, wait);
            tween.SetEase(AnimationCurve.EaseInOut(0f, 0f, wait, 1f));
            yield return new WaitForSeconds(wait);
        }
    }

    private void Update() {
        var fwd = cam.forward;
        fwd.y = 0f;
        
        if(fwd.sqrMagnitude > 0f) {
            float angle = Mathf.Atan2(fwd.z, fwd.x) * Mathf.Rad2Deg - 90f;
            handle.rotation = Quaternion.Lerp(handle.rotation, Quaternion.Euler(0f, 0f, -1 * angle + randomRot), Time.deltaTime * 5f);
        }
    }
}
