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

public class Game09 : MonoBehaviour{

    public GameObject particles;
    public GameObject death;
    public float turnSpeed;
    int currentRail = -1;
    public GameObject enemy;

    // Start is called before the first frame update
    void Start(){
        for (int i = 0; i < 10; i++){
            int position = Random.Range(-1, 1);
            if(position == 0){
                position = 1;
            }
            Instantiate(enemy, new Vector2(position, 6 + 5 * i), Quaternion.identity);
        }
    }

    // Update is called once per frame
    void Update(){
        if (Input.GetKeyDown(KeyCode.Space)){
            if(currentRail == -1){
                currentRail = 1;
            }else if(currentRail == 1){
                currentRail = -1;
            }
        }
        float fixedSpeed = turnSpeed * Time.deltaTime;
        transform.position = Vector3.MoveTowards(transform.position, new Vector2(currentRail, transform.position.y), fixedSpeed);
    }

    void OnCollisionEnter2D(Collision2D col){
        particles.SetActive(true);
        StartCoroutine(Death());
        GetComponent<SpriteRenderer>().enabled = false;
        GetComponent<CircleCollider2D>().enabled = false;
        AudioManager.instance.Play("Hit");
    }

    IEnumerator Death(){
        yield return new WaitForSecondsRealtime(1f);
        Time.timeScale = 0f;
        death.SetActive(true);
        death.SetActive(true);
        yield return new WaitForSecondsRealtime(4f);
        FindObjectOfType<GameController>().LoseGame();
    }
}
