using UnityEngine;
using System.Collections;

public class MouthMovement : MonoBehaviour {
    public Transform head;
    private Vector3 startRotation;
    private float val = 0.0f;
    private float lVal = 0.0f;
    private float moving = 0.0f;

    public void Start() {
        startRotation = transform.localEulerAngles;
    }

    public void LateUpdate() {
        AudioSource audioSource = head.GetComponent<AudioSource>();
        if (audioSource != null && audioSource.isPlaying) {
            moving = 1.0f;
            float v = audioSource.GetOutputData(256, 0)[255];
            if (v < 0) {
                v = 0.0f;
            }
            if (v > 0.033f) {
                v = 0.033f;
            }
            val = Mathf.Lerp(val, v * 333.0f, Time.deltaTime * 5);  //9
            lVal = Mathf.Lerp(lVal, Random.Range(-0.5f, 1.0f), Time.deltaTime * 4); //7
            transform.localEulerAngles = startRotation - new Vector3(val, 0.0f, 0.0f);
            transform.localScale = new Vector3(1.0f - ((val / 18.0f) * lVal), transform.localScale.y, transform.localScale.z);
        }
        else if (moving>0.0f) {
            transform.localEulerAngles = Vector3.Lerp(transform.localEulerAngles, startRotation, Time.deltaTime*3.0f);
            moving -= Time.deltaTime;
        }
    }
}