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

public class RotateAnim : MonoBehaviour
 {
    
    bool StopAnim = false;

    const float UseFixedDeltaTime = 1 / 60f;
    float originalFixedDeltaTime ;

    // Use this for initialization
    void Start () {
        
        StopAnim = true;

        originalFixedDeltaTime = Time.fixedDeltaTime;
        Time.fixedDeltaTime = UseFixedDeltaTime;
    }

    private void OnDestroy()
    {
        Time.fixedDeltaTime = originalFixedDeltaTime;
    }
    

    /// <summary>
    /// 瞬时力的衰减速度
    /// </summary>
    public float vAtten = 1;

    /// <summary>
    /// 物体质量
    /// </summary>
    float m = 1;

    List<RotateVelocity> m_VelocityList = new List<RotateVelocity>();
    /// <summary>
    /// 增加一个瞬时旋转力
    /// </summary>
    public void AddMomentaryForce(RotateForce force)
    {
        float v = force.power / m;//转速与质量成反比，与力成正比

        RotateVelocity newV = new RotateVelocity(force.axis, v);

        m_VelocityList.Add(newV);

        StopAnim = false;
    }

    /// <summary>
    /// 停止运动
    /// </summary>
    void Stop()
    {
        m_VelocityList.Clear();
        StopAnim = true;
    }
    

    Queue<Vector3> m_MomentaryRotateVec = new Queue<Vector3>();
    Queue<Vector3> GetForceRotateVector()
    {
        for (int i = 0; i < m_VelocityList.Count; i++)
        {
            RotateVelocity velocity = m_VelocityList[i];
            Vector3 vMove = velocity.v * Time.fixedDeltaTime * velocity.axis;
            velocity.Atten(vAtten);

            m_MomentaryRotateVec.Enqueue(vMove);
        }
        for (int i = 0; i < m_VelocityList.Count; )
        {
            RotateVelocity velocity = m_VelocityList[i];
            if (velocity.v <= 0)
            {
                m_VelocityList.RemoveAt(i);
            }
            else
            {
                i++;
            }
        }
        return m_MomentaryRotateVec;
    }
    
    // Update is called once per frame
	void FixedUpdate () {

        if (StopAnim)
            return;

        if (Time.fixedDeltaTime > UseFixedDeltaTime + 0.0001f)//避免误差
        {
            return;
        }
        
        //瞬时力的旋转运动
        var forceMove = GetForceRotateVector();
        while (forceMove.Count > 0)
        {
            Vector3 forceRot = forceMove.Dequeue();

            transform.Rotate(forceRot.normalized,forceRot.magnitude * Mathf.Rad2Deg);
        }
    }
}

public class RotateForce
{
    public Vector3 axis;
    public float power;

    public RotateForce(Vector3 axis, float power)
    {
        this.axis = axis;
        this.power = power;
    }
}

[System.Serializable]
public class RotateVelocity
{
    public Vector3 axis;
    public float v;

    public RotateVelocity(Vector3 axis,float v)
    {
        this.axis = axis.normalized;
        this.v = v;
    }

    public void Atten(float f)
    {
        v -= f;
    }
}