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

public class moveInvadersScript : MonoBehaviour
{

    private GameObject[] invaders;

    public float movementSpeed = 1f; // move once per second
    public float horizontalMovemnetStep = 0.2f;
    public float verticalMovementStep = 0.2f;
    private float movementTimer = 0f;

    float directionX = 1f;
    float directionY = 0f;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        movementTimer += Time.deltaTime;

        if (movementTimer > movementSpeed)
        {
            invaders = GameObject.FindGameObjectsWithTag("Enemy");
            int numVaders = invaders.Length;
            float minX = 100f;
            float maxX = -100f;
 
            foreach (GameObject vader in invaders)
            {
                float thisX = vader.GetComponent<Rigidbody2D>().position.x;

                if (thisX > maxX) { maxX = thisX; }
                if (thisX < minX) { minX = thisX; }
            }

            if (maxX > 8f) { directionX = -1f; directionY = -1f; }
            if (minX < -8f) { directionX = 1f; directionY = -1f; }

            foreach (GameObject vader in invaders)
            {
                vader.GetComponent<Rigidbody2D>().transform.Translate(new Vector3(directionX, directionY, 0));

            }

            if (numVaders == 0)
            {
                this.GetComponent<BuildLevelScript>().setupLevel();
            }

            directionY = 0f;

            movementTimer = 0f;
        }

    }
}
