import { _decorator, Component, Node, Button, Tween, tween, Vec3 } from 'cc'; const { ccclass, property } = _decorator; @ccclass('ButtonManager') export class ButtonManager extends Component { private static _instance: ButtonManager = null; @property({ type: [Button], displayName: "按钮数组" }) public buttons: Button[] = []; // 动画参数 private readonly SCALE_DOWN = 0.85; // 缩小到原来的0.85倍(相当于缩小1.5倍的倒数) private readonly ANIMATION_DURATION = 0.1; // 动画持续时间 public static get instance(): ButtonManager { return ButtonManager._instance; } onLoad() { // 设置单例 if (ButtonManager._instance === null) { ButtonManager._instance = this; } else { this.destroy(); return; } // 初始化按钮事件 this.initButtonEvents(); } onDestroy() { if (ButtonManager._instance === this) { ButtonManager._instance = null; } } private initButtonEvents() { this.buttons.forEach((button, index) => { if (button && button.node) { // 添加点击事件监听 button.node.on(Button.EventType.CLICK, () => { this.playClickAnimation(button.node); }, this); // 确保按钮初始缩放为1 button.node.setScale(Vec3.ONE); } }); } /** * 播放按钮点击动画 * @param buttonNode 按钮节点 */ private playClickAnimation(buttonNode: Node) { if (!buttonNode) return; // 停止之前的动画 Tween.stopAllByTarget(buttonNode); // 创建缩放动画:先缩小到0.85倍,然后回到原来大小 tween(buttonNode) .to(this.ANIMATION_DURATION, { scale: new Vec3(this.SCALE_DOWN, this.SCALE_DOWN, 1) }) .to(this.ANIMATION_DURATION, { scale: Vec3.ONE }) .start(); } /** * 手动添加按钮到管理器 * @param button 要添加的按钮 */ public addButton(button: Button) { if (button && this.buttons.indexOf(button) === -1) { this.buttons.push(button); // 为新添加的按钮设置事件 if (button.node) { button.node.on(Button.EventType.CLICK, () => { this.playClickAnimation(button.node); }, this); button.node.setScale(Vec3.ONE); } } } /** * 从管理器中移除按钮 * @param button 要移除的按钮 */ public removeButton(button: Button) { const index = this.buttons.indexOf(button); if (index !== -1) { // 移除事件监听 if (button.node) { button.node.off(Button.EventType.CLICK, this.playClickAnimation, this); } this.buttons.splice(index, 1); } } /** * 清空所有按钮 */ public clearAllButtons() { this.buttons.forEach(button => { if (button && button.node) { button.node.off(Button.EventType.CLICK, this.playClickAnimation, this); } }); this.buttons = []; } }