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_REDUCTION = 0.15; // 缩放减少量 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); // 不强制设置初始缩放,保持按钮原有缩放 } }); } /** * 播放按钮点击动画 * @param buttonNode 按钮节点 */ private playClickAnimation(buttonNode: Node) { if (!buttonNode) return; // 停止之前的动画 Tween.stopAllByTarget(buttonNode); // 获取当前缩放值 const currentScale = buttonNode.scale; const originalScale = currentScale.clone(); // 计算目标缩放值(当前缩放减去0.15) const targetScale = new Vec3( Math.max(0.1, currentScale.x - this.SCALE_REDUCTION), // 最小缩放限制为0.1 Math.max(0.1, currentScale.y - this.SCALE_REDUCTION), currentScale.z ); // 创建缩放动画:先缩小,然后回到原来大小 tween(buttonNode) .to(this.ANIMATION_DURATION, { scale: targetScale }) .to(this.ANIMATION_DURATION, { scale: originalScale }) .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); // 不强制设置缩放,保持按钮原有缩放 } } } /** * 从管理器中移除按钮 * @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 = []; } }