Files
vampire-like/Assets/GameMain/Scripts/Runtime/EntityLogic/TargetableObject.cs
T
2026-09-18 21:43:22 +08:00

107 lines
3.2 KiB
C#

using SepCore.Battle;
using SepCore.Components;
using SepCore.Definition;
using SepCore.CustomUtility;
using UnityEngine;
namespace SepCore.Entity
{
/// <summary>
/// 可作为目标的实体类。
/// </summary>
public abstract class TargetableObject : EntityBase
{
protected abstract TargetableObjectData _targetableObjectData { get; }
public bool IsDead => _healthComponent.CurrentHealth <= 0;
protected HealthComponent _healthComponent;
public abstract ImpactData GetImpactData();
public void ApplyDamage(EntityBase attacker, in DamageResult damageResult, Vector3? hitPosition = null)
{
if (damageResult.IsDodge)
{
_healthComponent.TakeDamage(0, false, true, hitPosition);
return;
}
float fromHPRatio = _healthComponent.HealthRatio;
_healthComponent.TakeDamage(damageResult.Damage, damageResult.IsCrit, false, hitPosition);
float toHPRatio = _healthComponent.HealthRatio;
if (fromHPRatio > toHPRatio)
{
GameEntry.HPBar.ShowHPBar(this, fromHPRatio, toHPRatio);
}
if (damageResult.IsLifeSteal && attacker != null)
{
HealthComponent attackerHealth = attacker.GetComponent<HealthComponent>();
if (attackerHealth == null && attacker is WeaponBase weapon)
{
attackerHealth = weapon.GetComponentInParent<HealthComponent>();
}
if (attackerHealth != null)
{
attackerHealth.TryTriggerLifeSteal(damageResult.LifeStealAmount);
}
}
if (_healthComponent.CurrentHealth <= 0)
{
OnDead(attacker);
}
}
public void ApplyDamage(EntityBase attacker, int damageHP)
{
ApplyDamage(attacker, new DamageResult
{
Damage = damageHP,
IsDodge = false,
IsCrit = false,
IsLifeSteal = false,
LifeStealAmount = 0
});
}
protected override void OnInit(object userData)
{
base.OnInit(userData);
_healthComponent = GetComponent<HealthComponent>();
}
protected override void OnShow(object userData)
{
base.OnShow(userData);
}
protected virtual void OnDead(EntityBase attacker)
{
GameEntry.Entity.HideEntity(this);
}
private void OnTriggerEnter(Collider other)
{
EntityBase entity = other.GetComponentInParent<EntityBase>();
if (entity == null || entity == this)
{
return;
}
if (entity is TargetableObject && entity.Id < Id)
{
// 碰撞事件由 Id 大的一方处理
// 在这里约定 Enemy 的 Id 为非负数(通常从 0 开始)
// 而其他的 Entity (Player, Weapon, Bullet) 的 Id 均小于 0
return;
}
AIUtility.PerformCollision(this, entity);
}
}
}