EntitiesComponent.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  1. using FL.Battle;
  2. using FL.Battle.Components;
  3. using FL.Battle.Skills;
  4. using FL.Data;
  5. using FL.Nodes.GameMain;
  6. using System;
  7. using System.Collections.Generic;
  8. using UnityEngine;
  9. using XGame;
  10. using XGame.Database;
  11. using XGame.Framework.Asyncs;
  12. using XGame.Framework.Components;
  13. using XGame.Framework.Map;
  14. using XGame.Framework.Time;
  15. namespace FL.Map.TestMainMap
  16. {
  17. public interface IEntitiesContext
  18. {
  19. IMapAssetModule Asset { get; }
  20. ITimeModule Time { get; }
  21. TestMainMapVM VM { get; }
  22. VfxComponent Vfx { get; }
  23. MapUIComponent MapUI { get; }
  24. }
  25. public partial class EntitiesComponent : Component<IEntitiesContext>
  26. {
  27. /// <summary>
  28. /// 怪物的位置相对于玩家战斗位置的偏移值
  29. /// </summary>
  30. private const float MONSTER_POSITION_OFFSET = 6;
  31. private PlayerEntityView _player;
  32. private Dictionary<long, PartnerEntityView> _partnerMap = new();
  33. private Dictionary<long, MonsterEntityView> _monsterMap = new();
  34. /// <summary>
  35. /// 地图实例对象,怪物、陷阱、召唤兽等
  36. /// key:UID
  37. /// </summary>
  38. private Dictionary<long, IEntityView> _entityViewsMap = new();
  39. private TargetSelector _selector;
  40. private ITimer _selectorTimer;
  41. protected override void OnEnable(object intent)
  42. {
  43. InitSelector();
  44. EventSingle.Instance.AddListener(EventDefine.GameMainMapLoadEntities, OnLoadEntities);
  45. EventSingle.Instance.AddListener(EventDefine.GameMainMapRemoveEntity, OnRemoveEntity);
  46. EventSingle.Instance.AddListener(EventDefine.GameMainMapRemoveSimpleEntity, OnRemoveSimpleEntity);
  47. EventSingle.Instance.AddListener(EventDefine.GameMainMapStartMask, OnStartMask);
  48. EventSingle.Instance.AddListener(EventDefine.GameMainMapGenBullet, OnGenBullet);
  49. EventSingle.Instance.AddListener(EventDefine.GameMainMapGenCommons, OnGenCommons);
  50. EventSingle.Instance.AddListener(EventDefine.GameMainMapAddBuff, OnAddBuff);
  51. EventSingle.Instance.AddListener(EventDefine.GameMainMapRemoveBuff, OnRemoveBuff);
  52. EventSingle.Instance.AddListener(EventDefine.GameMainMapReqPreviewBuffs, OnRequestBuffList);
  53. }
  54. protected override void OnDisable()
  55. {
  56. EventSingle.Instance.RemoveListener(EventDefine.GameMainMapLoadEntities, OnLoadEntities);
  57. EventSingle.Instance.RemoveListener(EventDefine.GameMainMapRemoveEntity, OnRemoveEntity);
  58. EventSingle.Instance.RemoveListener(EventDefine.GameMainMapRemoveSimpleEntity, OnRemoveSimpleEntity);
  59. EventSingle.Instance.RemoveListener(EventDefine.GameMainMapStartMask, OnStartMask);
  60. EventSingle.Instance.RemoveListener(EventDefine.GameMainMapGenBullet, OnGenBullet);
  61. EventSingle.Instance.RemoveListener(EventDefine.GameMainMapGenCommons, OnGenCommons);
  62. EventSingle.Instance.RemoveListener(EventDefine.GameMainMapAddBuff, OnAddBuff);
  63. EventSingle.Instance.RemoveListener(EventDefine.GameMainMapRemoveBuff, OnRemoveBuff);
  64. EventSingle.Instance.RemoveListener(EventDefine.GameMainMapReqPreviewBuffs, OnRequestBuffList);
  65. ClearSelector();
  66. Context.VM.Camera.Target = null;
  67. Context.Asset.Recycle(_player);
  68. foreach (var partner in _partnerMap.Values)
  69. {
  70. Context.Asset.Recycle(partner);
  71. }
  72. _partnerMap.Clear();
  73. foreach (var monster in _monsterMap.Values)
  74. {
  75. Context.Asset.Recycle(monster);
  76. }
  77. _monsterMap.Clear();
  78. foreach (var entity in _entityViewsMap.Values)
  79. {
  80. Context.Asset.Recycle(entity);
  81. }
  82. _entityViewsMap.Clear();
  83. ClearElementBuffs();
  84. }
  85. protected override void OnDispose()
  86. {
  87. }
  88. #region 事件监听
  89. private void OnLoadEntities(int eventId, object args)
  90. {
  91. var dto = (LoadEntitiesDto)args;
  92. if (dto.isPlayerMove)
  93. {
  94. ClearVfxs();
  95. }
  96. Context.MapUI.RefreshChapter(dto.chapterId);
  97. var asyncGroup = new AsyncGroup();
  98. if (dto.player != null)
  99. { // 第一波怪物,玩家不存在时
  100. var playerAsync = Context.Asset.LoadEntity<PlayerEntityView>(AddressableDefine.Player, Context.VM.PlayerRoot);
  101. playerAsync.On(_ =>
  102. {
  103. var entityView = playerAsync.Result;
  104. if (entityView == null)
  105. {
  106. return;
  107. }
  108. entityView.Entity = dto.player;
  109. Context.VM.Camera.Target = entityView.Move;// behaviour.transform;
  110. _player = entityView;
  111. _selector.Register(entityView);
  112. entityView.Selector = _selector;
  113. Context.MapUI.AddEntity(entityView);
  114. });
  115. playerAsync.Join(asyncGroup);
  116. }
  117. else if (dto.isChapterChanged)
  118. {
  119. Context.VM.Reset();
  120. _player.Reset();
  121. Context.MapUI.RefreshEntity(_player.Entity.EntityId);
  122. foreach (var item in _partnerMap)
  123. {
  124. item.Value.Reset();
  125. }
  126. }
  127. else if (dto.isBossPart)
  128. { // 重置玩家的血量
  129. _player.Reset(true);
  130. Context.MapUI.RefreshEntity(_player.Entity.EntityId);
  131. }
  132. var partnerCount = dto.partners?.Length ?? 0;
  133. if (partnerCount > 0)
  134. { // 创建伙伴实例
  135. for (var i = 0; i < partnerCount; i++)
  136. {
  137. var partner = dto.partners[i];
  138. var table = PartnerTableRepo.Get(partner.TableId);
  139. var loadAsync = Context.Asset.LoadEntity<PartnerEntityView>(table.Model, Context.VM.PlayerRoot);
  140. loadAsync.On(_ =>
  141. {
  142. var entityView = loadAsync.Result;
  143. if (entityView == null)
  144. {
  145. return;
  146. }
  147. entityView.Entity = partner;
  148. entityView.BodyMirror();
  149. _partnerMap.Add(partner.EntityId, entityView);
  150. _selector.Register(entityView);
  151. entityView.Selector = _selector;
  152. });
  153. loadAsync.Join(asyncGroup);
  154. }
  155. }
  156. var monsterCount = dto.monsters?.Length ?? 0;
  157. if (monsterCount > 0)
  158. { // 创建怪物实例
  159. for (var i = 0; i < monsterCount; i++)
  160. {
  161. var monster = dto.monsters[i];
  162. var table = MonsterTableRepo.Get(monster.TableId);
  163. var loadAsync = Context.Asset.LoadEntity<MonsterEntityView>(table.Model, Context.VM.EnemyRoot);
  164. loadAsync.On(_ =>
  165. {
  166. var entityView = loadAsync.Result;
  167. if (entityView == null)
  168. {
  169. return;
  170. }
  171. entityView.Entity = monster;
  172. entityView.Entity = monster;
  173. _monsterMap.Add(monster.EntityId, entityView);
  174. _selector.Register(entityView);
  175. entityView.Selector = _selector;
  176. if (table.Type == 1)
  177. { //boss的血条等boss移动到战斗位置再加载
  178. Context.MapUI.AddEntity(entityView);
  179. }
  180. });
  181. loadAsync.Join(asyncGroup);
  182. }
  183. }
  184. asyncGroup.On(_ =>
  185. {
  186. //Entities加载完成,开始移动
  187. if (dto.isPlayerMove)
  188. {
  189. _player.Reset(true);
  190. var moveArgs = new MoveArgs()
  191. {
  192. target = Context.VM.PlayerRoot.TransformPoint(dto.battlePosition)
  193. };
  194. _player.CommonAI.MoveToBattle(moveArgs, () =>
  195. {
  196. if (dto.isChapterChanged)
  197. {
  198. Context.VM.SetFocusPosition(_player.Position);
  199. }
  200. });
  201. foreach (var item in _partnerMap)
  202. {
  203. var entityView = item.Value;
  204. var entity = entityView.Entity;
  205. var tarPosition = dto.battlePosition;
  206. tarPosition += PartnersData.Instance.GetPartnerOffset(entity.Attr.UID);
  207. // 本地坐标转世界坐标
  208. tarPosition = Context.VM.PlayerRoot.TransformPoint(tarPosition);
  209. entityView.Reset(true);
  210. moveArgs = new MoveArgs()
  211. {
  212. target = tarPosition,
  213. };
  214. entityView.CommonAI.MoveToBattle(moveArgs);
  215. }
  216. }
  217. else if (partnerCount > 0)
  218. {
  219. for (var pIdx = 0; pIdx < partnerCount; pIdx++)
  220. {
  221. var entity = dto.partners[pIdx];
  222. var entityView = _partnerMap[entity.EntityId];
  223. entityView.CommonAI.PrepareBattle();
  224. }
  225. }
  226. //var monsterCount = dto.monsters?.Length ?? 0;
  227. for (var mIdx = 0; mIdx < monsterCount; mIdx++)
  228. {
  229. var entity = dto.monsters[mIdx];
  230. //var monsterTable = MonsterTableRepo.Get(entity.TableId);
  231. var tarPosition = entity.BirthPosition;
  232. tarPosition.y += (-dto.monsterMoveDistance + MONSTER_POSITION_OFFSET);
  233. tarPosition = Context.VM.EnemyRoot.TransformPoint(tarPosition);
  234. var entityView = _monsterMap[entity.EntityId];
  235. var moveArgs = new MoveArgs()
  236. {
  237. target = tarPosition,
  238. delay = entity.BirthDelay,
  239. };
  240. if (entity.BirthCurve > 0)
  241. {
  242. moveArgs.moveType = EMoveType.Curve;
  243. moveArgs.curve = Context.VM.MapPathCurve.GetCurve(entity.BirthCurve - 1);
  244. moveArgs.curveOffset = new Vector3(3, 0, 0);
  245. }
  246. entityView.CommonAI.MoveToBattle(moveArgs, () =>
  247. {
  248. if (entity.IsBoss)
  249. {
  250. Context.MapUI.AddBoss(entityView, dto.chapterId);
  251. }
  252. });
  253. }
  254. });
  255. asyncGroup.End();
  256. }
  257. private void OnRemoveEntity(int eventId, object args)
  258. {
  259. var entityId = (long)args;
  260. if (_monsterMap.TryGetValue(entityId, out var monster))
  261. {
  262. _monsterMap.Remove(entityId);
  263. _selector?.Unregister(monster);
  264. Context.Asset.Recycle(monster);
  265. RemoveElementBuff(entityId);
  266. return;
  267. }
  268. if (_partnerMap.TryGetValue(entityId, out var partner))
  269. {
  270. _partnerMap.Remove(entityId);
  271. _selector?.Unregister(partner);
  272. Context.Asset.Recycle(partner);
  273. return;
  274. }
  275. //if (entityId == _player?.Entity.EntityId)
  276. //{ // 玩家死亡只设置状态,不移除
  277. // _selector?.Unregister(_player);
  278. // Context.Asset.Recycle(_player);
  279. // _player = null;
  280. // Context.VM.Camera.Target = null;
  281. //}
  282. }
  283. private void OnRemoveSimpleEntity(int eventId, object args)
  284. {
  285. var entityId = (long)args;
  286. if (_entityViewsMap.TryGetValue(entityId, out var entityView))
  287. {
  288. _entityViewsMap.Remove(entityId);
  289. Context.Asset.Recycle(entityView);
  290. }
  291. }
  292. #endregion
  293. #region 目标选择
  294. private void InitSelector()
  295. {
  296. if (_selector == null)
  297. {
  298. _selector = new TargetSelector();
  299. }
  300. _selectorTimer = Context.Time.AddLooperTimer(100, _selector.OnUpdate);
  301. }
  302. private void ClearSelector()
  303. {
  304. _selector?.Clear();
  305. _selectorTimer?.Cancel();
  306. _selectorTimer = null;
  307. }
  308. #endregion
  309. #region 黑屏
  310. private void OnStartMask(int eventId, object args)
  311. {
  312. var sign = (EMapCombatSign)args;
  313. var duration = 2;
  314. ClearVfxs();
  315. if (sign is EMapCombatSign.Success)
  316. {
  317. PlayerMoveToCenter(duration);
  318. }
  319. else
  320. { // 玩家死亡,失败, 重置随从
  321. _player?.Reset();//
  322. foreach (var entity in _partnerMap.Values)
  323. {
  324. entity.Reset();
  325. }
  326. // 清空怪物
  327. foreach (var item in _monsterMap)
  328. {
  329. var entityId = item.Key;
  330. var monster = item.Value;
  331. //_monsterMap.Remove(entityId);
  332. _selector?.Unregister(monster);
  333. Context.Asset.Recycle(monster);
  334. RemoveElementBuff(entityId);
  335. }
  336. _monsterMap.Clear();
  337. }
  338. Context.VM.ShowBlackMask(duration, () =>
  339. {
  340. EventSingle.Instance.Notify(EventDefine.GameMainMapEndMask, sign);
  341. });
  342. }
  343. /// <summary>
  344. /// 没有怪物了,直接清空所有特效
  345. /// </summary>
  346. private void ClearVfxs()
  347. {
  348. foreach (var item in _entityViewsMap)
  349. {
  350. Context.Asset.Recycle(item.Value);
  351. }
  352. _entityViewsMap.Clear();
  353. Context.Vfx.Stop();
  354. }
  355. /// <summary>
  356. /// 玩家移动到屏幕中心
  357. /// </summary>
  358. /// <param name="duration">单位:秒</param>
  359. private void PlayerMoveToCenter(float duration)
  360. {
  361. var centerPosition = Context.VM.Camera.TopCenterToWorldPosition();
  362. var distance = centerPosition.y - _player.Position.y;
  363. var speed = distance / duration;
  364. // 使用玩家世界坐标的z值
  365. centerPosition.z = _player.Position.z;
  366. //var targetPosition = Context.VM.PlayerRoot.InverseTransformPoint(centerPosition);
  367. //Log.Debug($"PlayerMoveToCenter Player World:{_player.Position} Local:{_player.LocalPosition} Center World:{centerPosition}");
  368. _player.CommonAI.MoveTo(new MoveArgs
  369. {
  370. target = centerPosition,
  371. speed = speed,
  372. timeScale = 1,
  373. });
  374. foreach (var item in _partnerMap)
  375. {
  376. var entityView = item.Value;
  377. var entity = entityView.Entity;
  378. var tarPosition = centerPosition;
  379. tarPosition += PartnersData.Instance.GetPartnerOffset(entity.Attr.UID);
  380. entityView.CommonAI.MoveTo(new MoveArgs
  381. {
  382. target = tarPosition,
  383. speed = speed,
  384. timeScale = 1,
  385. });
  386. }
  387. }
  388. #endregion
  389. #region 子弹
  390. private void OnGenBullet(int eventId, object args)
  391. {
  392. var dto = (GenBulletDto)args;
  393. var targetType = dto.masterType == EEntityType.Monster ? EEntityType.Player : EEntityType.Monster;
  394. var skill = SkillTableRepo.Get(dto.tableId);
  395. var skillVfx = SkillVfxsTableRepo.Get(dto.tableId);
  396. var loadAsync = Context.Asset.LoadEntity<BulletEntityView>(skillVfx.SkillVfx, Context.VM.BulletRoot);
  397. var startTime = Context.Time.GetNowTime();
  398. loadAsync.On(_ =>
  399. {
  400. var delay = dto.delay > 0 ? Mathf.Max(dto.delay - (int)(Context.Time.GetNowTime() - startTime), 0) : 0;
  401. var view = loadAsync.Result;
  402. if (view == null)
  403. return;
  404. //var tarEntity = _selector.GetTarget((int)dto.targetId);
  405. //if (tarEntity == null || tarEntity.Entity.State == EEntityState.Dead)
  406. //{
  407. // Context.Asset.Recycle(view);
  408. // Log.Debug($"子弹加载成功,但是目标已死亡。Master:{dto.masterId} Target:{dto.targetId} Bullet:{dto.tableId}");
  409. // return;
  410. //}
  411. view.UID = UIDDefine.New();
  412. view.MasterId = dto.masterId;
  413. view.TableId = dto.tableId;
  414. view.Selector = _selector;
  415. view.Position = dto.from;
  416. _entityViewsMap.Add(view.UID, view);
  417. //var tarPosition = dto.to;
  418. //if (skill.SkillVfxType == (int)ESkillVfxType.BulletMortar)
  419. //{ // 目标位置随机,以本节战斗位置为中心偏移
  420. // tarPosition = _player.Position; //玩家的坐标和本节战斗的位置重叠
  421. // if (dto.masterType != EEntityType.Monster)
  422. // {// 施法者是玩家或者随从
  423. // tarPosition += skillVfx.SkillVfxPositions[1].ToVector3();
  424. // }
  425. // tarPosition.x += UnityEngine.Random.Range(-4, 5);
  426. // tarPosition.y += UnityEngine.Random.Range(-2, 2);
  427. //}
  428. view.AI.Start(dto.targetId, dto.to, targetType, delay);
  429. });
  430. }
  431. #endregion
  432. #region 召唤物
  433. private void OnGenCommons(int eventId, object args)
  434. {
  435. var dto = (GenSummonsDto)args;
  436. var skill = SkillTableRepo.Get(dto.tableId);
  437. var skillVfxs = SkillVfxsTableRepo.Get(dto.tableId);
  438. //var targetType = dto.masterType == EEntityType.Monster ? EEntityType.Player : EEntityType.Monster;
  439. var battlePosition = _player.Position;//玩家的坐标和本节战斗的位置重叠
  440. for (var i = 0; i < dto.count; i++)
  441. {
  442. switch ((ESkillVfxType)skill.SkillVfxType)
  443. {
  444. case ESkillVfxType.Trap:
  445. {
  446. var to = _selector.RandomPosition(dto.masterType == EEntityType.Monster ? EEntityType.Player : EEntityType.Monster, i == 0);
  447. //if (dto.masterType != EEntityType.Monster)
  448. //{ // 施法者是玩家或者随从
  449. // to += skillVfxs.SkillVfxPositions[1].ToVector3();
  450. //}
  451. //// 陷阱位置随机
  452. //to.x += UnityEngine.Random.Range(-4, 5);
  453. //to.y += UnityEngine.Random.Range(-2, 2);
  454. LoadTrap(dto, skillVfxs.SkillVfx, to);
  455. }
  456. break;
  457. case ESkillVfxType.AOE:
  458. {
  459. if (skillVfxs.VfxFollowType == (int)EVfxFollowType.World)
  460. { // 坐标修改为本次战斗的世界坐标
  461. dto.from = battlePosition;
  462. }
  463. var aoeFrom = skillVfxs.SkillVfxPositions[0].ToVector3();
  464. var aoeTo = skillVfxs.SkillVfxPositions[1].ToVector3();
  465. if (dto.masterType == EEntityType.Monster)
  466. { // 怪物在上,玩家在下
  467. aoeFrom.y *= -1;
  468. aoeTo.y *= -1;
  469. }
  470. aoeTo += dto.from;
  471. dto.from += aoeFrom;
  472. LoadAOEEntity(dto, skillVfxs.SkillVfx, aoeTo);
  473. }
  474. break;
  475. case ESkillVfxType.AOENoMove:
  476. {
  477. var to = battlePosition;
  478. to += skillVfxs.SkillVfxPositions[0].ToVector3();
  479. dto.from = to;
  480. LoadAOEEntity(dto, skillVfxs.SkillVfx, to);
  481. }
  482. break;
  483. case ESkillVfxType.AOETarget:
  484. {
  485. var to = dto.from;
  486. LoadAOEEntity(dto, skillVfxs.SkillVfx, to);
  487. }
  488. break;
  489. default:
  490. throw new NotImplementedException();
  491. }
  492. }
  493. }
  494. private void LoadTrap(GenSummonsDto dto, string vfxName, Vector3 tarPosition)
  495. {
  496. var loadAsync = Context.Asset.LoadEntity<TrapEntityView>(vfxName, Context.VM.BulletRoot);
  497. loadAsync.On(_ =>
  498. {
  499. var view = loadAsync.Result;
  500. if (view == null)
  501. return;
  502. view.UID = UIDDefine.New();
  503. view.MasterId = dto.masterId;
  504. view.TableId = dto.tableId;
  505. view.Selector = _selector;
  506. view.Position = dto.from;
  507. _entityViewsMap.Add(view.UID, view);
  508. view.AI.Start(tarPosition, dto.targetType);
  509. });
  510. }
  511. private void LoadAOEEntity(GenSummonsDto dto, string vfxName, Vector3 tarPosition)
  512. {
  513. var loadAsync = Context.Asset.LoadEntity<AOEEntityView>(vfxName, Context.VM.BulletRoot);
  514. loadAsync.On(_ =>
  515. {
  516. var view = loadAsync.Result;
  517. if (view == null)
  518. return;
  519. view.UID = UIDDefine.New();
  520. view.MasterId = dto.masterId;
  521. view.TableId = dto.tableId;
  522. view.Selector = _selector;
  523. view.Position = dto.from;
  524. _entityViewsMap.Add(view.UID, view);
  525. view.AI.Start(tarPosition, dto.targetType);
  526. });
  527. }
  528. #endregion
  529. }
  530. }