找物源码导读Cocos Creator 3.8 · assets/scripts
0%
已读 0 / 424
目录— 个文件
目录加载中…
…/module/ani/AutoFade.ts
1import { _decorator, Component, Node, tween, Tween, UIOpacity } from 'cc';
2
3const { ccclass, property } = _decorator;
4
5/**
6 * 挂在节点上,让节点做循环「淡入淡出」动画(适合按钮、图标、奖励入口)
7 * - 以启用时的原始透明度为基准,先淡入再淡出
8 * - 支持首帧延迟与循环间隔
9 */
10@ccclass('AutoFade')
11export class AutoFade extends Component {
12
13 @property({
14 tooltip: '淡入阶段时长(秒)',
15 min: 0.01,
16 })
17 public fadeInDuration: number = 0.5;
18
19 @property({
20 tooltip: '淡出阶段时长(秒)',
21 min: 0.01,
22 })
23 public fadeOutDuration: number = 0.5;
24
25 @property({
26 tooltip: '每轮循环完成后的间隔时长(秒)',
27 min: 0.0,
28 })
29 public interval: number = 0.0;
30
31 @property({
32 tooltip: '组件启用后首次开始呼吸前延迟(秒)',
33 min: 0.0,
34 })
35 public startDelay: number = 0.0;
36
37 private _uiOpacity: UIOpacity | null = null;
38 private _originOpacity: number = 255;
39 private _tween: Tween<UIOpacity> | null = null;
40
41 onEnable() {
42 if (!this.node?.isValid) {
43 return;
44 }
45
46 this._uiOpacity = this.node.getComponent(UIOpacity);
47 if (!this._uiOpacity) {
48 this._uiOpacity = this.node.addComponent(UIOpacity);
49 }
50
51 this._originOpacity = this._uiOpacity.opacity;
52 this.StartTween();
53 }
54
55 onDisable() {
56 this._tween?.stop();
57 this._tween = null;
58
59 if (this._uiOpacity?.isValid) {
60 this._uiOpacity.opacity = this._originOpacity;
61 }
62 }
63
64 /** 开始循环淡入淡出 */
65 private StartTween(): void {
66 if (!this._uiOpacity?.isValid) {
67 return;
68 }
69
70 this._tween?.stop();
71 this._tween = null;
72
73 const target = this._uiOpacity;
74 const base = this._originOpacity;
75 const targetOpacity = 128; // 淡入到半透明
76 const inDur = Math.max(this.fadeInDuration, 0.01);
77 const outDur = Math.max(this.fadeOutDuration, 0.01);
78 const gap = Math.max(this.interval, 0);
79 const initialDelay = Math.max(this.startDelay, 0);
80
81 const oneCycle = tween(target)
82 .to(inDur, { opacity: targetOpacity }, { easing: 'sineInOut' })
83 .to(outDur, { opacity: base }, { easing: 'sineInOut' })
84 .delay(gap);
85
86 this._tween = tween(target)
87 .call(() => {
88 target.opacity = base;
89 })
90 .delay(initialDelay)
91 .repeatForever(oneCycle);
92
93 this._tween.start();
94 }
95}
讲解96 行
透明循环人工通读

AutoFade.ts

启用时查找或添加 UIOpacity,保存当时透明度后通过 tween 在固定值一百二十八与原值之间往返。配置控制两段时长和等待,状态保存在组件实例;所谓淡入不一定更亮,原透明度低于目标时反而增加,禁用后恢复原值。

先看 onEnable 的组件补建,再看 StartTween 固定目标和 onDisable 恢复。

特殊处理与易错点

  • 易错点目标固定为 128,不是零与全不透明之间切换。
  • 销毁禁用停止 tween 并恢复原透明度,但自动添加的 UIOpacity 会保留。
10注释挂在节点上,让节点做循环「淡入淡出」动画(适合按钮、图标、奖励入口) - 以启用时的原始透明度为基准,先淡入再淡出 - 支持首帧延迟与循环间隔
11注释AutoFade:挂在节点上,让节点做循环「淡入淡出」动画(适合按钮、图标、奖励入口) - 以启用时的原始透明
17属性fade In Duration(number):该模块的运行态字段。
23属性fade Out Duration(number):该模块的运行态字段。
29属性interval(number):该模块的运行态字段。
35属性开始 Delay(number):该模块的运行态字段。
37属性界面 Opacity(UIOpacity | null):该模块的运行态字段。
38属性本次启用时读取的透明度,停止后回写。
39属性tween(Tween<UIOpacity> | null):该模块的运行态字段。
41方法准备透明度组件并保存原值后启动往返动画。
55方法停止透明度动画并在组件仍有效时恢复原值。
65方法构造原透明度与固定半透明值之间的循环变化。