OutArea.ts 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. import { _decorator, Component, Node, tween, Vec3 } from 'cc';
  2. import { EventDispatcher } from 'db://assets/core_tgx/easy_ui_framework/EventDispatcher';
  3. import { GameEvent } from '../Enum/GameEvent';
  4. import { CocktailCup } from '../Component/CocktailCup';
  5. const { ccclass, property, executeInEditMode } = _decorator;
  6. @ccclass('OutArea')
  7. @executeInEditMode
  8. export class OutArea extends Component {
  9. @property(Node)
  10. outNodes: Node = null!;
  11. // 直接使用outNodes的子节点管理
  12. get cups() {
  13. return this.outNodes.children;
  14. }
  15. start() {
  16. this.registerEvent();
  17. }
  18. protected onDestroy(): void {
  19. EventDispatcher.instance.off(GameEvent.EVENT_FILL_UP, this.onFillUp, this);
  20. }
  21. private registerEvent(): void {
  22. EventDispatcher.instance.on(GameEvent.EVENT_FILL_UP, this.onFillUp, this);
  23. }
  24. private async onFillUp(): Promise<void> {
  25. console.log('补满');
  26. // 获取所有有效杯子
  27. const validCups = this.cups.filter(cup => cup.isValid);
  28. if (validCups.length === 0) return;
  29. // 找到最右边的杯子(x坐标最大的)
  30. const rightMostCup = validCups.reduce((prev, current) => {
  31. return prev.position.x > current.position.x ? prev : current;
  32. });
  33. const cocktailCup = rightMostCup.getComponent(CocktailCup);
  34. if (cocktailCup) {
  35. try {
  36. // 执行补满动画并等待完成
  37. await cocktailCup.fillUp();
  38. console.log('最右侧杯子已补满');
  39. } catch (e) {
  40. console.error('补满操作失败:', e);
  41. }
  42. }
  43. }
  44. update(deltaTime: number) {
  45. }
  46. // 排列方法为异步
  47. async arrangeCups() {
  48. const startX = 50;
  49. const spacing = 100;
  50. // 过滤掉已销毁的节点
  51. const validCups = this.cups.filter(cup => cup.isValid);
  52. await new Promise<void>(resolve => {
  53. let completed = 0;
  54. validCups.forEach((cup, index) => {
  55. const targetX = startX + index * spacing;
  56. tween(cup)
  57. .to(0.3, { position: new Vec3(targetX, 0, 0) }, { easing: 'sineOut' })
  58. .call(() => {
  59. if (++completed === validCups.length) resolve();
  60. })
  61. .start();
  62. });
  63. // 处理无动画的情况
  64. if (validCups.length === 0) resolve();
  65. });
  66. }
  67. addCup(cup: Node) {
  68. cup.setParent(this.outNodes);
  69. this.arrangeCups();
  70. }
  71. removeCup(cup: Node) {
  72. cup.removeFromParent();
  73. this.arrangeCups();
  74. }
  75. getCups() {
  76. return this.cups;
  77. }
  78. }