Newer
Older
DungeonShooting / DungeonShooting_Godot / src / game / role / enemy / state / AiTargetInViewState.cs
  1.  
  2. using Godot;
  3.  
  4. /// <summary>
  5. /// 目标在视野范围内, 发起攻击
  6. /// </summary>
  7. public class AiTargetInViewState : StateBase<Enemy, AiStateEnum>
  8. {
  9. /// <summary>
  10. /// 是否在视野内
  11. /// </summary>
  12. public bool IsInView;
  13. //导航目标点刷新计时器
  14. private float _navigationUpdateTimer = 0;
  15. private float _navigationInterval = 0.3f;
  16. public AiTargetInViewState() : base(AiStateEnum.AiTargetInView)
  17. {
  18. }
  19.  
  20. public override void Enter(AiStateEnum prev, params object[] args)
  21. {
  22. _navigationUpdateTimer = 0;
  23. IsInView = true;
  24. }
  25.  
  26. public override void PhysicsProcess(float delta)
  27. {
  28. var playerPos = GameApplication.Instance.Room.Player.GetCenterPosition();
  29. //更新玩家位置
  30. if (_navigationUpdateTimer <= 0)
  31. {
  32. //每隔一段时间秒更改目标位置
  33. _navigationUpdateTimer = _navigationInterval;
  34. if (Master.NavigationAgent2D.GetTargetLocation() != playerPos)
  35. {
  36. Master.NavigationAgent2D.SetTargetLocation(playerPos);
  37. }
  38. }
  39. else
  40. {
  41. _navigationUpdateTimer -= delta;
  42. }
  43.  
  44. if (!Master.NavigationAgent2D.IsNavigationFinished())
  45. {
  46. //计算移动
  47. var nextPos = Master.NavigationAgent2D.GetNextLocation();
  48. Master.LookTargetPosition(playerPos);
  49. Master.AnimatedSprite.Animation = AnimatorNames.Run;
  50. Master.Velocity = (nextPos - Master.GlobalPosition - Master.NavigationPoint.Position).Normalized() * Master.MoveSpeed;
  51. Master.CalcMove(delta);
  52. }
  53.  
  54. //检测玩家是否在视野内
  55. if (Master.IsInTailAfterViewRange(playerPos))
  56. {
  57. IsInView = !Master.TestViewRayCast(playerPos);
  58. //关闭射线检测
  59. Master.TestViewRayCastOver();
  60. }
  61. else
  62. {
  63. IsInView = false;
  64. }
  65.  
  66. if (IsInView)
  67. {
  68. Master.EnemyAttack();
  69. }
  70. else
  71. {
  72. ChangeStateLate(AiStateEnum.AiTailAfter);
  73. }
  74. }
  75.  
  76. public override void DebugDraw()
  77. {
  78. var playerPos = GameApplication.Instance.Room.Player.GetCenterPosition();
  79. Master.DrawLine(new Vector2(0, -8), Master.ToLocal(playerPos), Colors.Red);
  80. }
  81. }