EntitiesComponent.cs 20 KB

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