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

public class EnemyManager : MonoBehaviour
{
    [SerializeField] LayerMask blockLayer;
    [SerializeField] GameObject deathEffect;

    public enum DIRECTION_TYPE{
        STOP,//止まっている
        RIGHT,//右に進んでいる
        LEFT,//左に進んでいる
    }

    DIRECTION_TYPE direction = DIRECTION_TYPE.STOP;
    Rigidbody2D Rbody2D;
    float speed;

    private void Start(){
        Rbody2D = GetComponent<Rigidbody2D>();
        direction = DIRECTION_TYPE.RIGHT;        
    }

    void Update(){
        if(!IsGround()){
            ChengeDirection();
        }  
    }

    bool IsGround(){
        Vector3 startVec = transform.position + transform.right*0.9f * transform.localScale.x;
        Vector3 endVec = startVec - transform.up * 1f;
        return Physics2D.Linecast(startVec,endVec,blockLayer);
    }
    void ChengeDirection(){
        if(direction == DIRECTION_TYPE.RIGHT){
            direction = DIRECTION_TYPE.LEFT;
        }
        else if(direction == DIRECTION_TYPE.LEFT){
            direction = DIRECTION_TYPE.RIGHT;
        }       
    }
    public void DestroyEnemy(){
        Instantiate(deathEffect,this.transform.position,this.transform.rotation);

        Destroy(this.gameObject);
    }

    private void FixedUpdate(){
        switch(direction){
            case DIRECTION_TYPE.STOP:
                speed = 0;
            break;
            case DIRECTION_TYPE.RIGHT:
                speed = 2;
                transform.localScale = new Vector3(1,1,1);
            break;
            case DIRECTION_TYPE.LEFT:
                speed = -2;
                transform.localScale = new Vector3(-1,1,1);
            break;
        }
        Rbody2D.velocity = new Vector2(speed,Rbody2D.velocity.y);
    }
}