找物源码导读Cocos Creator 3.8 · assets/scripts
0%
已读 0 / 424
目录— 个文件
目录加载中…
…/contents/simple/fadeAction.ts
1
2
3import { Node, tween, TweenEasing, UIOpacity } from "cc";
4import BaseAction from "../baseAction";
5
6/**
7 * 数据
8 */
9export interface FadeAniUseData {
10 /**
11 * 隐藏透明度
12 */
13 hide?: number,
14 /**
15 * 显示透明度
16 */
17 show?: number,
18 /**
19 * 动画曲线
20 */
21 easing?: TweenEasing,
22}
23export default class FadeAction extends BaseAction {
24 /**
25 * 动画显示
26 */
27 protected show(node: Node, onComplete?: (target?: object | undefined) => void) {
28
29 let opacityComponent = node.getComponent(UIOpacity);
30 if (!opacityComponent) {
31 opacityComponent = node.addComponent(UIOpacity);
32 }
33 const useData: FadeAniUseData | undefined = this.currentConfig.useData;
34 const targetOpacity: number = useData?.show || 255;
35
36 opacityComponent.opacity = useData?.hide || 0;
37 return tween(opacityComponent).to(this.currentConfig.duration!, { opacity: targetOpacity }, { easing: useData?.easing || 'smooth', onComplete }).start();
38 }
39 /**
40 * 动画隐藏
41 */
42
43 protected hide(node: Node, onComplete?: (target?: object | undefined) => void) {
44
45 let opacityComponent = node.getComponent(UIOpacity);
46 if (!opacityComponent) {
47 opacityComponent = node.addComponent(UIOpacity);
48 }
49 const useData: FadeAniUseData | undefined = this.currentConfig.useData;
50
51 return tween(opacityComponent).to(this.currentConfig.duration!, { opacity: useData?.hide || 0 }, { easing: useData?.easing || 'smooth', onComplete }).start();
52 }
53
54
55}
讲解56 行
淡入淡出动作实现人工通读

fadeAction.ts

在节点上取或添加 UIOpacity 组件,用 tween 修改 opacity,实现从隐藏透明度到显示透明度的淡入和反向淡出。默认显示 255、隐藏 0,缓动为 smooth,透明度按 0 到 255 取值。

两个方法结构对称,先看 show 先把透明度置为隐藏值,再看 hide 的目标值。

特殊处理与易错点

13注释隐藏透明度
17注释显示透明度
21注释动画曲线
23注释FadeAction:FadeAction 是「基础动作」目录下的实现/辅助。辅助实现文件,配合同目录的入口类使用
27方法确保节点有 UIOpacity,先把透明度置为隐藏值,再在时长内缓动到显示值。
43方法在给定时长内把节点透明度缓动到隐藏值,默认 0,缓动为 smooth。