using UnityEngine;

public class HumanRunning : MonoBehaviour 
{
    public bool SoundFX = false;

    public float Frequency;
    public float Phase;
    public Vector3 Amplitude;

    private Vector3 restLocalPos;
    private Rigidbody2D rb;
    private float speedLimit;

	void Start () 
	{
        restLocalPos = transform.localPosition;
        rb = transform.root.GetComponent<Rigidbody2D>();
        speedLimit = transform.root.GetComponent<MoveController>().SpeedLimit;
    }

    bool fxForNeg = false;
	
	void Update () 
	{
        float speedFactor = Mathf.Min(1, rb.velocity.magnitude / speedLimit);
        if (speedFactor < 0.05)
            return;

        float wavex = (Time.time * (2 * Mathf.PI) * Frequency + Phase) % (2*Mathf.PI);
        float wavey = Mathf.Cos(wavex);

        if (transform.root == HumanControl.ActiveHuman)
        {

            if (SoundFX && wavey < 0 && !fxForNeg)
            {
                ScrambleKit.FX.SoundFX.PlaySound("Footstep");
                fxForNeg = true;
            }

            if (wavey > 0 && fxForNeg)
                fxForNeg = false;
        }

        transform.localPosition = new Vector3(
                                   restLocalPos.x + Amplitude.x * wavey * speedFactor,
                                   restLocalPos.y + Amplitude.y * wavey * speedFactor,
                                   restLocalPos.z
                               );
    }

}
