2025-02-25 21:54:18 +08:00

73 lines
1.6 KiB
C#

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<Character> OnhealthChange;
public UnityEvent<Transform> OnTakeDamage;//受伤事件
public UnityEvent OnDie;//死亡事件
private void Start()
{
currentHealth = maxHealth;
OnhealthChange?.Invoke(this);
}
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();
}
OnhealthChange?.Invoke(this);
}
//触发无敌
private void TriggerInvulnerable()
{
if(!invulnerable)
{
invulnerable = true;
invulnerableCounter = invulnerableDuration;
}
}
}