119 lines
4.1 KiB
TypeScript
119 lines
4.1 KiB
TypeScript
import { _decorator, Component, MeshRenderer, Material, Color, math } from "cc";
|
||
const { ccclass, property } = _decorator;
|
||
|
||
@ccclass("PulsatingHighlighter")
|
||
export class PulsatingHighlighter extends Component {
|
||
@property(Material)
|
||
redMaterial: Material = null!;
|
||
|
||
@property(Material)
|
||
yellowMaterial: Material = null!; // Новый желтый материал
|
||
|
||
private _originalMaterials: Material[] = [];
|
||
private _currentAlpha = 0;
|
||
private _direction = 1;
|
||
private _animationSpeed = 3; // Скорость изменения альфа-канала
|
||
|
||
// Статическая переменная для хранения активного (подсвеченного) экземпляра
|
||
private static _activeInstance: PulsatingHighlighter | null = null;
|
||
|
||
onLoad() {
|
||
this._storeOriginalMaterials();
|
||
}
|
||
|
||
private _storeOriginalMaterials() {
|
||
const renderer = this.node.getComponent(MeshRenderer);
|
||
if (!renderer) return;
|
||
|
||
this._originalMaterials = renderer.materials
|
||
.filter((m): m is Material => !!m)
|
||
.map((m) => {
|
||
const newMat = new Material();
|
||
newMat.copy(m);
|
||
return newMat;
|
||
});
|
||
}
|
||
|
||
public switchToColor(color: string) {
|
||
const renderer = this.node.getComponent(MeshRenderer);
|
||
if (!renderer) return;
|
||
|
||
// Если уже есть активный объект и он не этот, сбрасываем его подсветку
|
||
if (PulsatingHighlighter._activeInstance && PulsatingHighlighter._activeInstance !== this) {
|
||
PulsatingHighlighter._activeInstance.resetHighlight();
|
||
}
|
||
// Назначаем текущий объект активным
|
||
PulsatingHighlighter._activeInstance = this;
|
||
|
||
let selectedMaterial: Material | null = null;
|
||
|
||
// Выбираем нужный материал
|
||
if (color === "red" && this.redMaterial) {
|
||
selectedMaterial = this.redMaterial;
|
||
} else if (color === "yellow" && this.yellowMaterial) {
|
||
selectedMaterial = this.yellowMaterial;
|
||
} else {
|
||
console.warn(`⚠️ Неизвестный цвет "${color}", используем оригинальный.`);
|
||
return;
|
||
}
|
||
|
||
// Создаем и настраиваем материал для подсветки
|
||
const highlightMat = new Material();
|
||
highlightMat.copy(selectedMaterial);
|
||
renderer.materials = renderer.materials.map(() => highlightMat);
|
||
|
||
// Запускаем анимацию пульсации
|
||
this._currentAlpha = 0;
|
||
this._direction = 1;
|
||
this.schedule(this._updateAlpha, 0.016);
|
||
|
||
// Через 10 секунд возвращаем объект к оригинальному виду, если он до сих пор активен
|
||
this.scheduleOnce(() => {
|
||
if (PulsatingHighlighter._activeInstance === this) {
|
||
this.resetHighlight();
|
||
PulsatingHighlighter._activeInstance = null;
|
||
}
|
||
}, 10);
|
||
}
|
||
|
||
private _updateAlpha() {
|
||
this._currentAlpha += this._direction * this._animationSpeed;
|
||
this._currentAlpha = math.clamp(this._currentAlpha, 0, 255);
|
||
|
||
if (this._currentAlpha === 255 || this._currentAlpha === 0) {
|
||
this._direction *= -1;
|
||
}
|
||
|
||
const renderer = this.node.getComponent(MeshRenderer);
|
||
if (renderer) {
|
||
renderer.materials.forEach((mat) => {
|
||
const mainColor = mat?.getProperty("mainColor") as Color;
|
||
mainColor.a = this._currentAlpha;
|
||
mat?.setProperty("mainColor", mainColor);
|
||
});
|
||
}
|
||
}
|
||
|
||
// Метод для сброса подсветки (остановка анимации и восстановление оригинальных материалов)
|
||
public resetHighlight() {
|
||
this.unschedule(this._updateAlpha);
|
||
this.unscheduleAllCallbacks(); // Убираем оставшиеся вызовы scheduleOnce
|
||
this._restoreOriginalMaterials();
|
||
}
|
||
|
||
private _restoreOriginalMaterials() {
|
||
const renderer = this.node.getComponent(MeshRenderer);
|
||
if (!renderer) return;
|
||
|
||
renderer.materials = this._originalMaterials.map((m) => {
|
||
const mat = new Material();
|
||
mat.copy(m);
|
||
return mat;
|
||
});
|
||
}
|
||
|
||
onDestroy() {
|
||
this.unscheduleAllCallbacks();
|
||
}
|
||
}
|