EntitiesComponent.cs 22 KB

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