Files
Gen_Hack-and-Slash-Roguelite/Client/Assets/Scripts/AI/JobNode_AttackTarget.cs

63 lines
2.6 KiB
C#
Raw Normal View History

using Data;
using Managers;
namespace AI
{
/// <summary>
/// AI行为树叶子节点让 SelfEntity 向最近的敌对实体攻击一次。
/// </summary>
public class JobNode_AttackTarget : LeafNodeBase
{
private Entity.Entity _targetHostileEntity; // 目标敌对实体
/// <summary>
/// 执行攻击最近敌对目标的逻辑。
/// </summary>
/// <returns>行为树节点状态。</returns>
protected override Status ExecuteLeafLogic()
{
// 如果没有当前目标或者当前目标已无效null或死亡则需要重新寻找目标
if (!_targetHostileEntity || _targetHostileEntity.IsDead)
{
// 1. 寻找最近的敌对实体
var hostileEntityRecord = EntityManager.Instance.FindNearestEntityByRelation(
SelfEntity.currentDimensionId,
SelfEntity.entityPrefab,
Relation.Hostile);
// 如果没有找到敌对目标,任务失败
if (!hostileEntityRecord || !hostileEntityRecord.entity)
{
// Debug.Log($"[{SelfEntity.entityDef.defName}] 行为节点<攻击目标>: 未找到敌对目标。");
return Status.Failure; // 没有敌人可攻击
}
_targetHostileEntity = hostileEntityRecord.entity;
}
// 确保找到的目标仍然有效
if (!_targetHostileEntity || _targetHostileEntity.IsDead)
{
// 如果在找到后立即目标死亡(极小概率),或者某种原因导致目标失效,也视为失败
// Debug.Log($"[{SelfEntity.entityDef.defName}] 行为节点<攻击目标>: 目标 [{_targetHostileEntity?.entityDef?.defName ?? "未知"}] 在验证时无效。");
_targetHostileEntity = null; // 清除无效目标
return Status.Failure;
}
// 2. 设置攻击方向
// 攻击方向是从 SelfEntity 指向目标实体
SelfEntity.attackDirection = _targetHostileEntity.Position - SelfEntity.Position;
// 3. 尝试攻击
var attackInitiated = SelfEntity.TryAttack();
return attackInitiated ? Status.Success : Status.Failure;
}
/// <summary>
/// 重置此攻击节点的所有内部状态。
/// </summary>
public override void Reset()
{
base.Reset(); // 调用基类的 Reset
_targetHostileEntity = null; // 清除目标
}
}
}