65 lines
1.9 KiB
C#
65 lines
1.9 KiB
C#
#if GRAPH_DESIGNER
|
||
using Opsive.BehaviorDesigner.Runtime.Tasks;
|
||
using Opsive.BehaviorDesigner.Runtime.Tasks.Actions;
|
||
using BaseGames.Enemies;
|
||
using UnityEngine;
|
||
|
||
namespace BaseGames.Enemies.AI
|
||
{
|
||
/// <summary>
|
||
/// BD Action:敌人巡逻行为。
|
||
/// 持续令敌人向当前朝向移动,遇墙/边缘时自动转向。
|
||
/// </summary>
|
||
public class BD_Patrol : Action
|
||
{
|
||
[Tooltip("检测地面边缘的向下射线长度")]
|
||
public float edgeCheckLength = 1.2f;
|
||
[Tooltip("检测障碍物的水平射线长度")]
|
||
public float wallCheckLength = 0.4f;
|
||
[Tooltip("地面/墙壁 LayerMask")]
|
||
public LayerMask groundLayer;
|
||
|
||
private EnemyBase _enemy;
|
||
private float _dir = 1f;
|
||
|
||
public override void OnStart()
|
||
{
|
||
_enemy = GetComponent<EnemyBase>();
|
||
}
|
||
|
||
public override TaskStatus OnUpdate()
|
||
{
|
||
if (_enemy == null) return TaskStatus.Failure;
|
||
|
||
if (ShouldFlip())
|
||
_dir = -_dir;
|
||
|
||
_enemy.MoveInDirection(_dir);
|
||
return TaskStatus.Running;
|
||
}
|
||
|
||
public override void OnEnd()
|
||
{
|
||
_enemy?.StopMovement();
|
||
}
|
||
|
||
private bool ShouldFlip()
|
||
{
|
||
Transform t = _enemy.transform;
|
||
Vector2 pos = t.position;
|
||
|
||
// 前方边缘检测:在脚前方向下射线,若无地面则转向
|
||
Vector2 edgeOrigin = pos + Vector2.right * (_dir * 0.3f) + Vector2.down * 0.1f;
|
||
bool hasGround = Physics2D.Raycast(edgeOrigin, Vector2.down, edgeCheckLength, groundLayer);
|
||
if (!hasGround) return true;
|
||
|
||
// 前方障碍检测:水平射线,若撞墙则转向
|
||
bool hitWall = Physics2D.Raycast(pos, Vector2.right * _dir, wallCheckLength, groundLayer);
|
||
if (hitWall) return true;
|
||
|
||
return false;
|
||
}
|
||
}
|
||
}
|
||
#endif
|