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

/**
 * SOURCE: https://medium.com/nice-things-ios-android-development/basic-2d-screen-shake-in-unity-9c27b56b516
 */
public class ScreenShake : MonoBehaviour
{
     // Transform of the GameObject you want to shake
    private new Transform transform;
    
    // Desired duration of the shake effect
    private float shakeDuration = 0f;
    
    // A measure of magnitude for the shake. Tweak based on your preference
    public float shakeMagnitude = 0.7f;
    
    // The initial position of the GameObject
    Vector3 initialPosition;

    private void OnEnable() {
        initialPosition = transform.localPosition;
    }

    void Awake()
    {
        if (transform == null)
        {
            transform = GetComponent(typeof(Transform)) as Transform;
        }
    }

    void Update() {
        if (shakeDuration > 0) {
            transform.localPosition = initialPosition + (Vector3)(Random.insideUnitCircle * shakeMagnitude);
            
            shakeDuration -= Time.deltaTime;
        } else {
            shakeDuration = 0f;
            transform.localPosition = initialPosition;
        }
    }

    public void TriggerShake(float forDuration = 2f) {
        shakeDuration = forDuration;
    }
}
