105 lines
3.2 KiB
TypeScript
105 lines
3.2 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; // Скорость изменения альфа-канала
|
|
|
|
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;
|
|
|
|
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(() => {
|
|
this._restoreOriginalMaterials();
|
|
this.unschedule(this._updateAlpha);
|
|
}, 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 color = mat?.getProperty('mainColor') as Color;
|
|
color.a = this._currentAlpha;
|
|
mat?.setProperty('mainColor', color);
|
|
});
|
|
}
|
|
}
|
|
|
|
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();
|
|
}
|
|
}
|