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

public class Character : MonoBehaviour
{
    [Header("基本属性")]
    public float maxHealth;
    public float currentHealth;

    [Header("受伤无敌")]
    public float invulnerableDuration;//无敌时间
    private float invulnerableCounter;//计数器
    public bool invulnerable;//无敌

    public UnityEvent<Transform> OnTakeDamage;//受伤事件
    public UnityEvent OnDie;//死亡事件

    private void Start()
    {
        currentHealth = maxHealth;
    }


    private void Update()
    {
        if (invulnerable)
        {
            invulnerableCounter -= Time.deltaTime;
            if(invulnerableCounter <= 0)
            {
                invulnerable = false;
            }
        }
    }

    //接收伤害
    public void TakeDamage(Attack attacker)
    {
        if(invulnerable)
        {
            return;
        }
        if(currentHealth - attacker.damage > 0)//如果血量满足受伤就可以受伤
        {
            currentHealth -= attacker.damage;
            TriggerInvulnerable();
            //执行受伤
            OnTakeDamage?.Invoke(attacker.transform);
        }
        else
        {
            currentHealth = 0;//触发死亡
            OnDie?.Invoke();
        }
       
    }

    //触发无敌
    private void TriggerInvulnerable()
    {
        if(!invulnerable)
        {
            invulnerable = true;
            invulnerableCounter = invulnerableDuration;
        }
    }
}
