RemainComponent.ts 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import { _decorator, Component, instantiate, Node, Prefab } from 'cc';
  2. import { EventDispatcher } from 'db://assets/core_tgx/easy_ui_framework/EventDispatcher';
  3. import { GameEvent } from '../Enum/GameEvent';
  4. import { LevelManager } from '../Manager/LevelMgr';
  5. import { UI_BattleResult } from 'db://assets/scripts/UIDef';
  6. import { tgxUIMgr } from 'db://assets/core_tgx/tgx';
  7. const { ccclass, property } = _decorator;
  8. @ccclass('RemainComponent')
  9. export class RemainComponent extends Component {
  10. @property(Prefab)
  11. public remainPrefab: Prefab = null;
  12. private remainCount: number = 0; // 剩余数量
  13. protected onLoad(): void {
  14. EventDispatcher.instance.on(GameEvent.EVENT_INIT_REMAIN_ENEMY, this.initializeRemainCount, this);
  15. EventDispatcher.instance.on(GameEvent.EVENT_CAMERA_SHOOT_ENEMY, this.reduceCount, this);
  16. }
  17. start() {
  18. }
  19. private initializeRemainCount(count:number): void {
  20. this.remainCount = count;
  21. this.initRemainCount(this.remainCount);
  22. }
  23. private initRemainCount(remainCount: number): void {
  24. this.remainCount = remainCount;
  25. this.updateRemainCount();
  26. }
  27. private updateRemainCount(): void {
  28. // 先清空所有子节点
  29. this.node.removeAllChildren();
  30. // 根据剩余数量实例化预设
  31. for (let i = 0; i < this.remainCount; i++) {
  32. const item = instantiate(this.remainPrefab);
  33. this.node.addChild(item);
  34. }
  35. }
  36. public reduceCount(): boolean {
  37. if (this.remainCount <= 0) {
  38. return false;
  39. }
  40. // 获取最后一个实例化的节点
  41. const lastChild = this.node.children[this.remainCount - 1];
  42. if (lastChild) {
  43. const deathNode = lastChild.getChildByName('Death');
  44. const activeNode = lastChild.getChildByName('Active');
  45. if (deathNode && activeNode) {
  46. deathNode.active = true;
  47. activeNode.active = false;
  48. }
  49. }
  50. this.remainCount--;
  51. if(this.remainCount <= 0){
  52. LevelManager.instance.levelModel.isWin = true;
  53. const revive = tgxUIMgr.inst.isShowing(UI_BattleResult);
  54. if (!revive) {
  55. tgxUIMgr.inst.showUI(UI_BattleResult);
  56. }
  57. }
  58. return true;
  59. }
  60. protected onDestroy(): void {
  61. EventDispatcher.instance.off(GameEvent.EVENT_INIT_REMAIN_ENEMY, this.initializeRemainCount, this);
  62. EventDispatcher.instance.off(GameEvent.EVENT_CAMERA_SHOOT_ENEMY, this.reduceCount, this);
  63. }
  64. }