Newer
Older
DungeonShooting / DungeonShooting_Godot / src / game / activity / role / enemy / Enemy.cs
@小李xl 小李xl on 20 Nov 2023 15 KB 第二种敌人死亡动作,开发中
  1. #region 基础敌人设计思路
  2. /*
  3. 敌人有三种状态:
  4. 状态1: 未发现玩家, 视野不可穿墙, 该状态下敌人移动比较规律, 移动速度较慢, 一旦玩家进入视野或者听到玩家枪声, 立刻切换至状态3, 该房间的敌人不能再回到状态1
  5. 状态2: 发现有玩家, 但不知道在哪, 视野不可穿墙, 该情况下敌人移动速度明显加快, 移动不规律, 一旦玩家进入视野或者听到玩家枪声, 立刻切换至状态3
  6. 状态3: 明确知道玩家的位置, 视野允许穿墙, 移动速度与状态2一致, 进入该状态时, 敌人之间会相互告知玩家所在位置, 并朝着玩家位置开火,
  7. 如果有墙格挡, 则有一定概率继续开火, 一旦玩家立刻敌人视野超哥一段时间, 敌人自动切换为状态2
  8.  
  9. 敌人状态1只存在于少数房间内, 比如特殊房间, 大部分情况下敌人应该是状态2, 或者玩家进入房间时就被敌人发现
  10. */
  11. #endregion
  12.  
  13.  
  14. using EnemyState;
  15. using Godot;
  16.  
  17. /// <summary>
  18. /// 高级敌人,可以携带武器
  19. /// </summary>
  20. [Tool]
  21. public partial class Enemy : Role
  22. {
  23. /// <summary>
  24. /// 目标是否在视野内
  25. /// </summary>
  26. public bool TargetInView { get; set; } = true;
  27. /// <summary>
  28. /// 敌人身上的状态机控制器
  29. /// </summary>
  30. public StateController<Enemy, AIStateEnum> StateController { get; private set; }
  31.  
  32. /// <summary>
  33. /// 视野半径, 单位像素, 发现玩家后改视野范围可以穿墙
  34. /// </summary>
  35. public float ViewRange { get; set; } = 250;
  36.  
  37. /// <summary>
  38. /// 发现玩家后跟随玩家的视野半径
  39. /// </summary>
  40. public float TailAfterViewRange { get; set; } = 400;
  41.  
  42. /// <summary>
  43. /// 背后的视野半径, 单位像素
  44. /// </summary>
  45. public float BackViewRange { get; set; } = 50;
  46.  
  47. /// <summary>
  48. /// 是否可以拾起武器
  49. /// </summary>
  50. [Export]
  51. public bool CanPickUpWeapon { get; set; } = true;
  52. /// <summary>
  53. /// 视野检测射线, 朝玩家打射线, 检测是否碰到墙
  54. /// </summary>
  55. [Export, ExportFillNode]
  56. public RayCast2D ViewRay { get; set; }
  57.  
  58. /// <summary>
  59. /// 导航代理
  60. /// </summary>
  61. [Export, ExportFillNode]
  62. public NavigationAgent2D NavigationAgent2D { get; set; }
  63.  
  64. /// <summary>
  65. /// 导航代理中点
  66. /// </summary>
  67. [Export, ExportFillNode]
  68. public Marker2D NavigationPoint { get; set; }
  69.  
  70. /// <summary>
  71. /// 不通过武发射子弹的开火点
  72. /// </summary>
  73. [Export, ExportFillNode]
  74. public Marker2D FirePoint { get; set; }
  75. /// <summary>
  76. /// 当前敌人所看向的对象, 也就是枪口指向的对象
  77. /// </summary>
  78. public ActivityObject LookTarget { get; set; }
  79.  
  80. /// <summary>
  81. /// 攻击锁定目标时间
  82. /// </summary>
  83. public float LockingTime { get; set; } = 1f;
  84. /// <summary>
  85. /// 锁定目标已经走过的时间
  86. /// </summary>
  87. public float LockTargetTime { get; set; } = 0;
  88.  
  89. public override void OnInit()
  90. {
  91. base.OnInit();
  92. IsAi = true;
  93.  
  94. if (!CanPickUpWeapon)
  95. {
  96. WeaponPack.SetCapacity(0);
  97. }
  98. StateController = AddComponent<StateController<Enemy, AIStateEnum>>();
  99.  
  100. AttackLayer = PhysicsLayer.Wall | PhysicsLayer.Player;
  101. EnemyLayer = PhysicsLayer.Player;
  102. Camp = CampEnum.Camp2;
  103.  
  104. RoleState.MoveSpeed = 20;
  105.  
  106. MaxHp = 20;
  107. Hp = 20;
  108.  
  109. //注册Ai状态机
  110. StateController.Register(new AiNormalState());
  111. StateController.Register(new AiTailAfterState());
  112. StateController.Register(new AiFollowUpState());
  113. StateController.Register(new AiLeaveForState());
  114. StateController.Register(new AiSurroundState());
  115. StateController.Register(new AiFindAmmoState());
  116. StateController.Register(new AiAttackState());
  117. StateController.Register(new AiAstonishedState());
  118. StateController.Register(new AiNotifyState());
  119. //默认状态
  120. StateController.ChangeStateInstant(AIStateEnum.AiNormal);
  121. }
  122.  
  123. public override void EnterTree()
  124. {
  125. if (!World.Enemy_InstanceList.Contains(this))
  126. {
  127. World.Enemy_InstanceList.Add(this);
  128. }
  129. }
  130.  
  131. public override void ExitTree()
  132. {
  133. World.Enemy_InstanceList.Remove(this);
  134. }
  135.  
  136. protected override void OnDie()
  137. {
  138. //扔掉所有武器
  139. var weapons = WeaponPack.GetAndClearItem();
  140. for (var i = 0; i < weapons.Length; i++)
  141. {
  142. weapons[i].ThrowWeapon(this);
  143. }
  144.  
  145. var effPos = Position + new Vector2(0, -Altitude);
  146. //血液特效
  147. var blood = ObjectManager.GetPoolItem<AutoDestroyParticles>(ResourcePath.prefab_effect_enemy_EnemyBlood0001_tscn);
  148. blood.Position = effPos - new Vector2(0, 12);
  149. blood.AddToActivityRoot(RoomLayerEnum.NormalLayer);
  150. blood.PlayEffect();
  151.  
  152. //创建敌人碎片
  153. var count = Utils.Random.RandomRangeInt(3, 6);
  154. for (var i = 0; i < count; i++)
  155. {
  156. var debris = Create(Ids.Id_enemy_dead0001);
  157. debris.PutDown(effPos, RoomLayerEnum.NormalLayer);
  158. debris.InheritVelocity(this);
  159. }
  160. //派发敌人死亡信号
  161. EventManager.EmitEvent(EventEnum.OnEnemyDie, this);
  162. Destroy();
  163. }
  164.  
  165. protected override void Process(float delta)
  166. {
  167. base.Process(delta);
  168. if (IsDie)
  169. {
  170. return;
  171. }
  172. //看向目标
  173. if (LookTarget != null && MountLookTarget)
  174. {
  175. var pos = LookTarget.Position;
  176. LookPosition = pos;
  177. //脸的朝向
  178. var gPos = Position;
  179. if (pos.X > gPos.X && Face == FaceDirection.Left)
  180. {
  181. Face = FaceDirection.Right;
  182. }
  183. else if (pos.X < gPos.X && Face == FaceDirection.Right)
  184. {
  185. Face = FaceDirection.Left;
  186. }
  187. //枪口跟随目标
  188. MountPoint.SetLookAt(pos);
  189. }
  190.  
  191. //拾起武器操作
  192. EnemyPickUpWeapon();
  193. }
  194.  
  195. public override bool IsAllWeaponTotalAmmoEmpty()
  196. {
  197. if (!CanPickUpWeapon)
  198. {
  199. return false;
  200. }
  201. return base.IsAllWeaponTotalAmmoEmpty();
  202. }
  203.  
  204. protected override void OnHit(ActivityObject target, int damage, float angle, bool realHarm)
  205. {
  206. //受到伤害
  207. var state = StateController.CurrState;
  208. if (state == AIStateEnum.AiNormal || state == AIStateEnum.AiLeaveFor) //|| state == AiStateEnum.AiProbe
  209. {
  210. LookTarget = target;
  211. StateController.ChangeState(AIStateEnum.AiTailAfter);
  212. }
  213. }
  214.  
  215. /// <summary>
  216. /// 返回地上的武器是否有可以拾取的, 也包含没有被其他敌人标记的武器
  217. /// </summary>
  218. public bool CheckUsableWeaponInUnclaimed()
  219. {
  220. foreach (var unclaimedWeapon in World.Weapon_UnclaimedWeapons)
  221. {
  222. //判断是否能拾起武器, 条件: 相同的房间
  223. if (unclaimedWeapon.AffiliationArea == AffiliationArea)
  224. {
  225. if (!unclaimedWeapon.IsTotalAmmoEmpty())
  226. {
  227. if (!unclaimedWeapon.HasSign(SignNames.AiFindWeaponSign))
  228. {
  229. return true;
  230. }
  231. else
  232. {
  233. //判断是否可以移除该标记
  234. var enemy = unclaimedWeapon.GetSign<Enemy>(SignNames.AiFindWeaponSign);
  235. if (enemy == null || enemy.IsDestroyed) //标记当前武器的敌人已经被销毁
  236. {
  237. unclaimedWeapon.RemoveSign(SignNames.AiFindWeaponSign);
  238. return true;
  239. }
  240. else if (!enemy.IsAllWeaponTotalAmmoEmpty()) //标记当前武器的敌人已经有新的武器了
  241. {
  242. unclaimedWeapon.RemoveSign(SignNames.AiFindWeaponSign);
  243. return true;
  244. }
  245. }
  246. }
  247. }
  248. }
  249.  
  250. return false;
  251. }
  252. /// <summary>
  253. /// 寻找可用的武器
  254. /// </summary>
  255. public Weapon FindTargetWeapon()
  256. {
  257. Weapon target = null;
  258. var position = Position;
  259. foreach (var weapon in World.Weapon_UnclaimedWeapons)
  260. {
  261. //判断是否能拾起武器, 条件: 相同的房间, 或者当前房间目前没有战斗, 或者不在战斗房间
  262. if (weapon.AffiliationArea == AffiliationArea)
  263. {
  264. //还有弹药
  265. if (!weapon.IsTotalAmmoEmpty())
  266. {
  267. //查询是否有其他敌人标记要拾起该武器
  268. if (weapon.HasSign(SignNames.AiFindWeaponSign))
  269. {
  270. var enemy = weapon.GetSign<Enemy>(SignNames.AiFindWeaponSign);
  271. if (enemy == this) //就是自己标记的
  272. {
  273.  
  274. }
  275. else if (enemy == null || enemy.IsDestroyed) //标记当前武器的敌人已经被销毁
  276. {
  277. weapon.RemoveSign(SignNames.AiFindWeaponSign);
  278. }
  279. else if (!enemy.IsAllWeaponTotalAmmoEmpty()) //标记当前武器的敌人已经有新的武器了
  280. {
  281. weapon.RemoveSign(SignNames.AiFindWeaponSign);
  282. }
  283. else //放弃这把武器
  284. {
  285. continue;
  286. }
  287. }
  288.  
  289. if (target == null) //第一把武器
  290. {
  291. target = weapon;
  292. }
  293. else if (target.Position.DistanceSquaredTo(position) >
  294. weapon.Position.DistanceSquaredTo(position)) //距离更近
  295. {
  296. target = weapon;
  297. }
  298. }
  299. }
  300. }
  301.  
  302. return target;
  303. }
  304.  
  305. /// <summary>
  306. /// 获取武器攻击范围 (最大距离值与最小距离的中间值)
  307. /// </summary>
  308. /// <param name="weight">从最小到最大距离的过渡量, 0 - 1, 默认 0.5</param>
  309. public float GetWeaponRange(float weight = 0.5f)
  310. {
  311. if (WeaponPack.ActiveItem != null)
  312. {
  313. var attribute = WeaponPack.ActiveItem.Attribute;
  314. return Mathf.Lerp(Utils.GetConfigRangeStart(attribute.Bullet.DistanceRange), Utils.GetConfigRangeEnd(attribute.Bullet.DistanceRange), weight);
  315. }
  316.  
  317. return 0;
  318. }
  319.  
  320. /// <summary>
  321. /// 返回目标点是否在视野范围内
  322. /// </summary>
  323. public bool IsInViewRange(Vector2 target)
  324. {
  325. var isForward = IsPositionInForward(target);
  326. if (isForward)
  327. {
  328. if (GlobalPosition.DistanceSquaredTo(target) <= ViewRange * ViewRange) //没有超出视野半径
  329. {
  330. return true;
  331. }
  332. }
  333.  
  334. return false;
  335. }
  336.  
  337. /// <summary>
  338. /// 返回目标点是否在跟随状态下的视野半径内
  339. /// </summary>
  340. public bool IsInTailAfterViewRange(Vector2 target)
  341. {
  342. var isForward = IsPositionInForward(target);
  343. if (isForward)
  344. {
  345. if (GlobalPosition.DistanceSquaredTo(target) <= TailAfterViewRange * TailAfterViewRange) //没有超出视野半径
  346. {
  347. return true;
  348. }
  349. }
  350.  
  351. return false;
  352. }
  353.  
  354. /// <summary>
  355. /// 调用视野检测, 如果被墙壁和其它物体遮挡, 则返回true
  356. /// </summary>
  357. public bool TestViewRayCast(Vector2 target)
  358. {
  359. ViewRay.Enabled = true;
  360. ViewRay.TargetPosition = ViewRay.ToLocal(target);
  361. ViewRay.ForceRaycastUpdate();
  362. return ViewRay.IsColliding();
  363. }
  364.  
  365. /// <summary>
  366. /// 调用视野检测完毕后, 需要调用 TestViewRayCastOver() 来关闭视野检测射线
  367. /// </summary>
  368. public void TestViewRayCastOver()
  369. {
  370. ViewRay.Enabled = false;
  371. }
  372.  
  373. /// <summary>
  374. /// AI 拾起武器操作
  375. /// </summary>
  376. private void EnemyPickUpWeapon()
  377. {
  378. //这几个状态不需要主动拾起武器操作
  379. var state = StateController.CurrState;
  380. if (state == AIStateEnum.AiNormal || state == AIStateEnum.AiNotify || state == AIStateEnum.AiAstonished || state == AIStateEnum.AiAttack)
  381. {
  382. return;
  383. }
  384. //拾起地上的武器
  385. if (InteractiveItem is Weapon weapon)
  386. {
  387. if (WeaponPack.ActiveItem == null) //手上没有武器, 无论如何也要拾起
  388. {
  389. TriggerInteractive();
  390. return;
  391. }
  392.  
  393. //没弹药了
  394. if (weapon.IsTotalAmmoEmpty())
  395. {
  396. return;
  397. }
  398. var index = WeaponPack.FindIndex((we, i) => we.ActivityBase.Id == weapon.ActivityBase.Id);
  399. if (index != -1) //与武器背包中武器类型相同, 补充子弹
  400. {
  401. if (!WeaponPack.GetItem(index).IsAmmoFull())
  402. {
  403. TriggerInteractive();
  404. }
  405.  
  406. return;
  407. }
  408.  
  409. // var index2 = Holster.FindWeapon((we, i) =>
  410. // we.Attribute.WeightType == weapon.Attribute.WeightType && we.IsTotalAmmoEmpty());
  411. var index2 = WeaponPack.FindIndex((we, i) => we.IsTotalAmmoEmpty());
  412. if (index2 != -1) //扔掉没子弹的武器
  413. {
  414. ThrowWeapon(index2);
  415. TriggerInteractive();
  416. return;
  417. }
  418. // if (Holster.HasVacancy()) //有空位, 拾起武器
  419. // {
  420. // TriggerInteractive();
  421. // return;
  422. // }
  423. }
  424. }
  425. /// <summary>
  426. /// 获取锁定目标的剩余时间
  427. /// </summary>
  428. public float GetLockRemainderTime()
  429. {
  430. var weapon = WeaponPack.ActiveItem;
  431. if (weapon == null)
  432. {
  433. return LockingTime - LockTargetTime;
  434. }
  435. return weapon.Attribute.AiAttackAttr.LockingTime - LockTargetTime;
  436. }
  437.  
  438. public override void LookTargetPosition(Vector2 pos)
  439. {
  440. LookTarget = null;
  441. base.LookTargetPosition(pos);
  442. }
  443. /// <summary>
  444. /// 执行移动操作
  445. /// </summary>
  446. public void DoMove()
  447. {
  448. AnimatedSprite.Play(AnimatorNames.Run);
  449. //计算移动
  450. var nextPos = NavigationAgent2D.GetNextPathPosition();
  451. BasisVelocity = (nextPos - Position - NavigationPoint.Position).Normalized() * RoleState.MoveSpeed;
  452. }
  453.  
  454. /// <summary>
  455. /// 执行站立操作
  456. /// </summary>
  457. public void DoIdle()
  458. {
  459. AnimatedSprite.Play(AnimatorNames.Idle);
  460. BasisVelocity = Vector2.Zero;
  461. }
  462. /// <summary>
  463. /// 更新房间中标记的目标位置
  464. /// </summary>
  465. public void UpdateMarkTargetPosition()
  466. {
  467. if (LookTarget != null)
  468. {
  469. AffiliationArea.RoomInfo.MarkTargetPosition[LookTarget.Id] = LookTarget.Position;
  470. }
  471. }
  472. }