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

public class PlayerAnimation : MonoBehaviour {

    public SpriteRenderer renderer;
    public Sprite[] sprites;
    PlayerController control;

    float initAngle;
    float bobSpeed = 8;
    float bobAmount = 10;
    float zAngle;

    float time;
    float step = 0.2f;

    // Start is called before the first frame update
    void Awake() {
        renderer = GetComponent<SpriteRenderer>();
        control = GetComponentInParent<PlayerController>();
        time = 0;

        initAngle = transform.eulerAngles.z;
        zAngle = initAngle;
    }

    // Update is called once per frame
    void Update() {
        if (control.forwards) {
            if (!control.isRunning) {
                renderer.sprite = sprites[0];
                time = 0;
                zAngle = 0;
            } else {
                //Moving
                renderer.sprite = sprites[1];
                time += Time.deltaTime;
                if (time > step) {
                    renderer.flipX = !renderer.flipX;
                    time = 0;
                }

                zAngle = Mathf.Sin(Time.time * bobSpeed) * bobAmount;
            }
        } else {
            if (!control.isRunning) {
                renderer.sprite = sprites[2];
                time = 0;
                zAngle = 0;
            } else {
                //Moving
                renderer.sprite = sprites[3];
                time += Time.deltaTime;
                if (time > step) {
                    renderer.flipX = !renderer.flipX;
                    time = 0;
                }

                zAngle = Mathf.Sin(Time.time * bobSpeed) * bobAmount;
            }
        }

        transform.rotation = Quaternion.Euler(
            transform.eulerAngles.x,
            transform.eulerAngles.y,
            zAngle
        );
    }
}
