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

public class WaypointMovement : MonoBehaviour {

    private bool dirRight = true;
    public float speed = 2.0f;
    public float timeOnWaypoint = 2;
    bool isWalking = true;
    public Animator anim;
    public Transform[] waypoints;


    private void Start()
    {
        anim = GetComponent<Animator>();
        anim.SetBool("Moving", isWalking);
    }

    void Update()
    {
        if (waypoints[0] == null)
            return;

        if (isWalking)
        {
        if (transform.position.x >= waypoints[0].position.x)
        {
            StartCoroutine(waitOnWaypoint());

        }
        else if (transform.position.x <= waypoints[1].position.x)
        {
            StartCoroutine(waitOnWaypoint());

        }
            if (dirRight)
                transform.Translate(Vector2.right * speed * Time.deltaTime);

            else
                transform.Translate(-Vector2.right * speed * Time.deltaTime);

        
       }

        
    }

     IEnumerator waitOnWaypoint()
    {
        isWalking = false;             
        anim.SetBool("Moving", isWalking);
        dirRight = !dirRight;

        yield return new WaitForSeconds(timeOnWaypoint * Time.deltaTime);
        Vector3 newScale = new Vector3(-transform.localScale.x, transform.localScale.y, transform.localScale.z);
        transform.localScale = newScale;        
        isWalking = true;
        anim.SetBool("Moving", isWalking);
    }

    }

