using System; using UnityEngine; public class EnemyController : MonoBehaviour { enum State { Spawning, Moving, Dying } [Range(0f, 10f)] public float moveSpeed = 2f; public Material flashMaterial; public Material defaultMaterial; public AudioClip hitSound; public AudioClip deadSound; GameObject target; State state; // Start is called once before the first execution of Update after the MonoBehaviour is created void Start() { //target = GameObject.Find("Player"); // target = GameObject.FindGameObjectWithTag("Player"); // state = State.Moving; } public void Spawn(GameObject target) { this.target = target; state = State.Spawning; GetComponent().Initalize(); GetComponent().SetTrigger("Spawn"); Invoke("StartMoving", 1f); GetComponent().enabled = false; } void StartMoving() { GetComponent().enabled = true; state = State.Moving; } private void FixedUpdate() { if (state == State.Moving) { Vector2 direction = target.transform.position - transform.position; transform.Translate(direction.normalized * (moveSpeed * Time.fixedDeltaTime), Space.World); if (direction.x < 0) { GetComponent().flipX = true; } else if (direction.x > 0) { GetComponent().flipX = false; } } } private void OnTriggerEnter2D(Collider2D collision) { Debug.Log("Hit"); if (collision.tag == "Bullet") { float d = collision.gameObject.GetComponent().damage; if(GetComponent().Hit(d)) { // 살아있을 때 Flash(); GetComponent().PlayOneShot(hitSound); } else { // 죽었을 때 Die(); GetComponent().PlayOneShot(deadSound); } } } void Flash() { GetComponent().material = flashMaterial; Invoke("AfterFlash", 0.5f); } void AfterFlash() { GetComponent().material = defaultMaterial; } void Die() { state = State.Dying; GetComponent().SetTrigger("Die"); // 일정 시간이 지난 후 호출하는 함수 Invoke("AfterDying", 1.4f); } void AfterDying() { // Destroy(gameObject); gameObject.SetActive(false); } // Update is called once per frame void Update() { } }