RemainComponent.ts 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. this.initializeRemainCount(); // 初始化剩余数量
  19. }
  20. private initializeRemainCount(): void {
  21. //TODO 获取本关卡初始数量
  22. this.remainCount = 6;
  23. this.initRemainCount(this.remainCount);
  24. }
  25. private initRemainCount(remainCount: number): void {
  26. this.remainCount = remainCount;
  27. this.updateRemainCount();
  28. }
  29. private updateRemainCount(): void {
  30. // 先清空所有子节点
  31. this.node.removeAllChildren();
  32. // 根据剩余数量实例化预设
  33. for (let i = 0; i < this.remainCount; i++) {
  34. const item = instantiate(this.remainPrefab);
  35. this.node.addChild(item);
  36. }
  37. }
  38. public reduceCount(): boolean {
  39. if (this.remainCount <= 0) {
  40. return false;
  41. }
  42. // 获取最后一个实例化的节点
  43. const lastChild = this.node.children[this.remainCount - 1];
  44. if (lastChild) {
  45. const deathNode = lastChild.getChildByName('Death');
  46. const activeNode = lastChild.getChildByName('Active');
  47. if (deathNode && activeNode) {
  48. deathNode.active = true;
  49. activeNode.active = false;
  50. }
  51. }
  52. this.remainCount--;
  53. if(this.remainCount <= 0){
  54. LevelManager.instance.levelModel.isWin = true;
  55. const revive = tgxUIMgr.inst.isShowing(UI_BattleResult);
  56. if (!revive) {
  57. tgxUIMgr.inst.showUI(UI_BattleResult);
  58. }
  59. }
  60. return true;
  61. }
  62. protected onDestroy(): void {
  63. EventDispatcher.instance.off(GameEvent.EVENT_INIT_REMAIN_ENEMY, this.initializeRemainCount, this);
  64. EventDispatcher.instance.off(GameEvent.EVENT_CAMERA_SHOOT_ENEMY, this.reduceCount, this);
  65. }
  66. }