#if GRAPH_DESIGNER
using UnityEngine;
using Opsive.BehaviorDesigner.Runtime.Tasks;
using Opsive.BehaviorDesigner.Runtime.Tasks.Actions;
using BaseGames.Enemies;
using BaseGames.Enemies.Perception;
namespace BaseGames.Enemies.AI
{
///
/// BD Action:来回踱步巡逻——持续向当前方向移动,遇墙或悬崖时自动翻转方向。
/// 转向检测依赖 EnemySensorHub 的 "wall_ahead" / "ledge" 槽(SensorToolkit)。
///
/// 若需要按预设路点顺序巡逻,请使用 (支持 Transform 引用和内联坐标)。
///
[TaskName("Patrol (Pace)")]
[TaskCategory("BaseGames/Enemy/Movement")]
[TaskDescription("来回踱步巡逻:遇墙或悬崖自动翻转方向(需配置 EnemySensorHub wall_ahead / ledge 槽)")]
public class BD_Patrol : Action
{
private EnemyBase _enemy;
private EnemySensorHub _hub;
private float _dir = 1f;
private float _flipCooldown; // 翻转后短暂冷却,等待 RaySensor2D 刷新到新朝向
// 缓存:SensorHub 中对应槽位是否已配置(Awake 时查询一次,避免每帧 Dictionary 查找)
private bool _hasWallSensor;
private bool _hasEdgeSensor;
public override void OnAwake()
{
_enemy = GetComponent();
_hub = GetComponent();
_hasWallSensor = _hub != null && _hub.Get(SensorSlotNames.WallAhead) != null;
_hasEdgeSensor = _hub != null && _hub.Get(SensorSlotNames.Ledge) != null;
}
public override void OnStart()
{
_enemy?.SetAiPhase(AiPhase.Patrol);
// 与敌人实际朝向同步,防止任务重入时 _dir 与朝向不符(如战斗后朝向已改变)
if (_enemy?.Movement != null)
_dir = _enemy.Movement.FacingDirection;
_flipCooldown = 0f;
}
public override TaskStatus OnUpdate()
{
if (_enemy == null) return TaskStatus.Failure;
// 翻转冷却期间跳过传感器检测(等待 RaySensor2D 在新朝向完成刷新)
if (_flipCooldown > 0f)
_flipCooldown -= Time.deltaTime;
else if (ShouldFlip())
{
_dir = -_dir;
_flipCooldown = 0.1f; // ~6 帧缓冲(60 fps),防止传感器残留信号导致抖动
}
_enemy.MoveInDirection(_dir);
return TaskStatus.Running;
}
public override void OnEnd() => _enemy?.StopMovement();
private bool ShouldFlip()
{
// 转身进行中时不重复检测,防止 _dir 在转身期间被传感器残留信号反复翻转
if (_enemy.Movement != null && _enemy.Movement.IsTurning) return false;
bool wallHit = _hasWallSensor && _hub.HasAnyDetection(SensorSlotNames.WallAhead);
bool edgeHit = _hasEdgeSensor && _hub.HasAnyDetection(SensorSlotNames.Ledge);
return wallHit || edgeHit;
}
}
}
#endif