using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraGravity : MonoBehaviour {

    public Vector2 gravity;
    public Vector2 origgravity;

    public bool upright;
    float falltime;

    public void Awake()
    {
        upright = true;
        origgravity = Physics2D.gravity;
        gravity = Physics2D.gravity;
    }

    public void StartRotation()
    {
        upright = false;
        falltime = Time.time;
    }

    public void Update()
    {
        if (upright)
        {
            SetGravityDirection(Physics2D.gravity + Random.insideUnitCircle * 0.001f);
            float a1 = Mathf.Atan2(gravity.y, origgravity.x);
            float a2 = Mathf.Atan2(gravity.y, origgravity.x);
            if (Mathf.Abs(a1 - a2) > 0.01f)
            {
                gravity = Vector2.Lerp(gravity, origgravity, 0.006f);
                SetGravityDirection(gravity);
            }
        } else
        {
            Vector2 wantgravity = (new Vector2(-origgravity.y, origgravity.x) - origgravity / 2).normalized;
            Vector2 sonow = Vector2.Lerp(gravity, wantgravity, 0.03f);
            SetGravityDirection(sonow);
        }
    }

    public void SetGravity(Vector2 grav)
    {
        gravity = grav;
        Physics2D.gravity = grav;
    }

    public void SetGravityDirection(Vector2 grav)
    {
        gravity = Physics2D.gravity;
        float prevrot = Mathf.Atan2(gravity.y, gravity.x);
        float nowrot = Mathf.Atan2(grav.y, grav.x);
        float rotationchange = nowrot - prevrot;

        float g = Physics2D.gravity.magnitude;
        gravity = grav.normalized * g;
        Physics2D.gravity = gravity;

        transform.Rotate(new Vector3(0, 0, rotationchange / (Mathf.PI * 2) * 360));
    }
}
