yantar/assets/Scripts/PulsatingHighlighter.ts

94 lines
3.3 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!;
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 switchToRed() {
const renderer = this.node.getComponent(MeshRenderer);
if (!renderer || !this.redMaterial) return;
// Создаем и настраиваем материал
const redMat = new Material();
redMat.copy(this.redMaterial);
redMat.initialize({
effectName: 'builtin-unlit',
defines: { USE_TRANSPARENT: true }
});
redMat.setProperty('mainColor', new Color(255, 0, 0, 0));
renderer.materials = renderer.materials.map(() => redMat);
// Запускаем анимацию
this._currentAlpha = 0;
this._direction = 1;
this.schedule(this._updateAlpha, 0.016);
// Возвращаем оригинал через 3 секунды
this.scheduleOnce(() => {
this._restoreOriginalMaterials();
this.unschedule(this._updateAlpha);
}, 10);
}
private _updateAlpha() {
this._currentAlpha += this._direction * this._animationSpeed;
// Ограничиваем значение между 0 и 255
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();
}
}