| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116 |
- 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 = [];
- }
- }
|