yantar/assets/Scripts/ux/MorphButtonWithButton.ts
2025-05-27 22:10:21 +07:00

147 lines
5.2 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { _decorator, Component, Sprite, SpriteFrame, tween, Button, Tween, Node, Color } from 'cc';
const { ccclass, property } = _decorator;
@ccclass('MorphButtonWithButton')
export class MorphButtonWithButton extends Component {
@property(SpriteFrame) questionFrame!: SpriteFrame;
@property(SpriteFrame) noiseFrame!: SpriteFrame;
@property(SpriteFrame) crossFrame!: SpriteFrame;
@property(Sprite) targetSprite!: Sprite;
private isQuestion = true;
private buttonId: string = '';
private currentTween: Tween<Node> | null = null;
onLoad() {
// Генерируем уникальный ID для кнопки
this.buttonId = `${this.node.name}_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;
console.log(`[MorphButton] onLoad: ${this.node.name} (${this.node.uuid}), buttonId: ${this.buttonId}`);
this.initializeSprite();
}
private initializeSprite() {
if (this.targetSprite && this.questionFrame) {
this.targetSprite.spriteFrame = this.questionFrame;
this.isQuestion = true;
}
}
public fullReinitialize() {
console.log(`[MorphButton] fullReinitialize START: ${this.node.name} (${this.node.uuid}), current state: ${this.isQuestion ? 'question' : 'cross'}`);
// Останавливаем все анимации
if (this.currentTween) {
this.currentTween.stop();
this.currentTween = null;
}
Tween.stopAllByTarget(this.targetSprite?.node);
// Полностью переинициализируем состояние
this.isQuestion = true;
this.currentTween = null;
// Переинициализируем спрайт
this.initializeSprite();
// Генерируем новый ID для отладки
this.buttonId = `${this.node.name}_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;
console.log(`[MorphButton] fullReinitialize COMPLETE: ${this.node.name}, new state: ${this.isQuestion ? 'question' : 'cross'}, buttonId: ${this.buttonId}`);
}
onDestroy() {
// Останавливаем все анимации при уничтожении
if (this.currentTween) {
this.currentTween.stop();
this.currentTween = null;
}
Tween.stopAllByTarget(this.targetSprite?.node);
}
public onClick() {
console.log(`[MorphButton] onClick: ${this.node.name} (${this.node.uuid}), buttonId: ${this.buttonId}, current state: ${this.isQuestion ? 'question' : 'cross'}`);
// Останавливаем предыдущую анимацию, если она есть
if (this.currentTween) {
this.currentTween.stop();
this.currentTween = null;
}
const frames = this.isQuestion
? [this.noiseFrame, this.crossFrame]
: [this.noiseFrame, this.questionFrame];
const dt = 0.055;
// Передаём цель – targetSprite.node, чтобы Tween точно запустился
let tw = tween(this.targetSprite.node);
for (const frame of frames) {
tw = tw
.delay(dt)
.call(() => {
this.targetSprite.spriteFrame = frame;
});
}
// Меняем состояние только после завершения анимации
tw = tw.call(() => {
this.isQuestion = !this.isQuestion;
console.log(`[MorphButton] Animation complete, new state: ${this.isQuestion ? 'question' : 'cross'}`);
});
// Сохраняем ссылку на текущий tween
this.currentTween = tw;
tw.start();
}
public resetState() {
console.log(`[MorphButton] resetState: ${this.node.name} (${this.node.uuid}), buttonId: ${this.buttonId}, was: ${this.isQuestion ? 'question' : 'cross'}`);
// Останавливаем любые активные анимации
if (this.currentTween) {
this.currentTween.stop();
this.currentTween = null;
}
// Останавливаем все tween на спрайте
Tween.stopAllByTarget(this.targetSprite.node);
// Сбрасываем состояние
this.isQuestion = true;
// Принудительно сбрасываем спрайт
this.forceResetSprite();
}
private forceResetSprite() {
if (!this.targetSprite || !this.questionFrame) {
console.warn('[MorphButton] Cannot reset sprite - missing targetSprite or questionFrame');
return;
}
// Метод 1: Прямая установка
this.targetSprite.spriteFrame = this.questionFrame;
// Метод 2: Очистка и повторная установка
this.targetSprite.spriteFrame = null;
this.scheduleOnce(() => {
if (this.targetSprite && this.questionFrame) {
this.targetSprite.spriteFrame = this.questionFrame;
console.log(`[MorphButton] Sprite reset complete`);
}
}, 0);
// Метод 3: Принудительное обновление через изменение других свойств
const originalColor = this.targetSprite.color.clone();
this.targetSprite.color = new Color(255, 255, 255, 254);
this.targetSprite.color = originalColor;
}
public getButtonId(): string {
return this.buttonId;
}
public getIsQuestion(): boolean {
return this.isQuestion;
}
}