using System;
using System.Collections;
using UnityEngine;
using Random = UnityEngine.Random;

public class CameraShake : MonoBehaviour
{

    public float maxAmplitude = 0.5f; // 最大振幅A
    
    // 抖动持续时间
    private float shakeDuration = 0f;
    private float currentShakeTime = 0f;

    private Vector3 initPos;

    private void Awake()
    {
        initPos = transform.localPosition;
    }

    private void Start()
    {
        //InvokeRepeating("StartShake",2,3f);
        //StartShake();
    }

    void Update()
    {
        /*   连续按不会有问题
        if (Input.GetMouseButton(0))
        {
            StartShake();
        }
        */
        
        if (currentShakeTime < shakeDuration)
        {
            // 更新抖动时间
            currentShakeTime += Time.deltaTime;
            
            // 计算当前振幅（随时间衰减）
           var currentAmplitude = maxAmplitude * (1 - currentShakeTime / shakeDuration);
            
           //var shakePhase = Random.Range(0, 2 * Mathf.PI);
            // 计算正弦抖动值,range是相位，f是频率，c是越来越小增幅
            var f = 3f;
            float shakeX = currentAmplitude * Mathf.Sin(f*Time.time+Random.Range(0, 2 * Mathf.PI));
            float shakeY = currentAmplitude * Mathf.Sin(f*Time.time+Random.Range(0, 2 * Mathf.PI) );
            float shakeZ = currentAmplitude * Mathf.Sin(Time.time * 0.8f);
            
            // 应用抖动到相机位置
            transform.localPosition = new Vector3(initPos.x+shakeX,initPos.y+shakeY,  initPos.z);
        }
        /*
        else if (currentShakeTime > 0)
        {
            // 抖动结束，重置位置
            transform.localPosition = initPos;
            currentShakeTime = 0;
            currentAmplitude = 0;
        }
        */
    }
    
    // 外部调用开始抖动
    public void StartShake()
    {
        transform.localPosition = initPos;
        currentShakeTime = 0;
        shakeDuration = 0.9f;
    }
}