EntitiesComponent.cs 23 KB

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