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

public class SoliderL : MonoBehaviour
{
Animator animator; // BS์˜ ์• ๋‹ˆ๋ฉ”์ดํ„ฐ ์ปดํฌ๋„ŒํŠธ
public bool isAttacking = false; // ๊ณต๊ฒฉ ์ค‘์ธ์ง€ ํ™•์ธํ•˜๋Š” ํ”Œ๋ž˜๊ทธ
Rigidbody2D rb;
public float speed = 1.5f;
public int health;
bool isDamage; // ๋ฌด์  ํƒ€์ž„ ์ฒ˜๋ฆฌ

void Start()
{
rb = GetComponent<Rigidbody2D>();
animator = GetComponent<Animator>(); // Animator ์ปดํฌ๋„ŒํŠธ ๊ฐ€์ ธ์˜ค๊ธฐ
}

void OnHit()
{
// Health Down
health--;
animator.SetTrigger("doHit");
Invoke("ReturnSprite", 0.2f);
if (health <= 0)
{
animator.SetTrigger("doDie");
Destroy(gameObject, 2f);
}
}

void ReturnSprite()
{
animator.SetTrigger("doStop"); // ์• ๋‹ˆ๋ฉ”์ด์…˜์ด ๋ฉˆ์ถ”๋Š” ๋ฉ”์„œ๋“œ
}

void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag("RedMelee"))
{
if (!isDamage)
{
//Bullet bullet = other.gameObject.GetComponent<Bullet>();
health -- ;
StartCoroutine(OnDamage());
OnHit();
Debug.Log("์™ผ์ชฝ์— ์žˆ๋Š” ๋ธ”๋ฃจํŒ€ ๋ณ‘์‚ฌ๊ฐ€ ๊ณต๊ฒฉ์„ ๋ฐ›์•˜์Šต๋‹ˆ๋‹ค.");
}
}
}

IEnumerator OnDamage()
{
isDamage = true;
// ํ”ผ๊ฒฉ ์ด๋ฒคํŠธ ์ƒ๋žต
yield return new WaitForSeconds(1f);
isDamage = false;
// ํ”ผ๊ฒฉ ์ด๋ฒคํŠธ์—์„œ ๋Œ์•„์˜ค๋Š”๊ฑฐ ์ƒ๋žต
}

void Update()
{
// BS๋ฅผ ์™ผ์ชฝ์œผ๋กœ ์ด๋™์‹œํ‚ค๊ธฐ
MoveLeft();
}

void MoveLeft()
{
// ํ˜„์žฌ ์†๋„๋ฅผ ์™ผ์ชฝ ๋ฐฉํ–ฅ์œผ๋กœ ์„ค์ •
rb.velocity = new Vector2(-speed, rb.velocity.y);
}

void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Enemy"))
{
if (!isAttacking) // ์ด๋ฏธ ๊ณต๊ฒฉ ์ค‘์ด ์•„๋‹ˆ๋ฉด ๊ณต๊ฒฉ ์‹œ์ž‘
{
isAttacking = true;
StartCoroutine(AttackRoutine()); // Coroutine ์‹œ์ž‘
}
}
}

void OnCollisionExit2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Enemy"))
{
StopAttack(); // ๊ณต๊ฒฉ ์ค‘์ง€
}
}

IEnumerator AttackRoutine()
{
while (isAttacking)
{
AttackDa();
yield return new WaitForSeconds(1f);
}
}

void AttackDa()
{
animator.SetTrigger("doAttack");
}

void StopAttack()
{
isAttacking = false; // ๊ณต๊ฒฉ ์ค‘์ง€
animator.ResetTrigger("doAttack"); // ์• ๋‹ˆ๋ฉ”์ด์…˜ ํŠธ๋ฆฌ๊ฑฐ ๋ฆฌ์…‹
}
}
์ด๊ฑฐ ์™œ 1์ดˆ์— ํ•œ๋ฒˆ์”ฉ ๋•Œ๋ ค์ง€๋Š”๊ฒŒ ์•„๋‹ˆ๋ผ
1์ดˆ์— ์—ฌ๋Ÿฌ๋ฒˆ์”ฉ ๋–„๋ ค์ง€๋Š”๊ฑฐ์ž„?
1์ดˆ์— 1๋ฒˆ์”ฉ ๋•Œ๋ ค์ง€๊ฒŒ ํ•˜๋ ค๋ฉด ์–ด๋–ป๊ฒŒ ํ•ด์•ผํ•จ? ์ œ๋ฐœ ๋„์™€์ฃผ์…ˆ